Skip to main content

vvv_engine/vfs/
memory.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3use std::sync::RwLock;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use super::{EntryKind, MoveError, MoveState, ParentCreation, Stamp, Vfs, VfsError};
7
8/// In-memory file tree. Paths are stored exactly as given. Every write and
9/// rename gives the file a fresh version, so stamps behave like mtimes.
10#[derive(Debug, Default)]
11pub struct MemoryVfs {
12    files: RwLock<BTreeMap<PathBuf, Entry>>,
13    versions: AtomicU64,
14}
15
16#[derive(Debug)]
17struct Entry {
18    contents: String,
19    version: u64,
20}
21
22impl MemoryVfs {
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// Builder-style insertion for fixtures.
28    pub fn with_file(self, path: impl Into<PathBuf>, contents: impl Into<String>) -> Self {
29        self.write(&path.into(), &contents.into())
30            .expect("MemoryVfs write cannot fail");
31        self
32    }
33
34    fn entry(&self, contents: String) -> Entry {
35        Entry {
36            contents,
37            version: self.versions.fetch_add(1, Ordering::Relaxed),
38        }
39    }
40}
41
42impl<P: Into<PathBuf>, S: Into<String>> FromIterator<(P, S)> for MemoryVfs {
43    fn from_iter<I: IntoIterator<Item = (P, S)>>(iter: I) -> Self {
44        iter.into_iter()
45            .fold(MemoryVfs::new(), |vfs, (path, contents)| {
46                vfs.with_file(path, contents)
47            })
48    }
49}
50
51impl Vfs for MemoryVfs {
52    fn read(&self, path: &Path) -> Result<String, VfsError> {
53        self.files
54            .read()
55            .expect("MemoryVfs lock poisoned")
56            .get(path)
57            .map(|e| e.contents.clone())
58            .ok_or_else(|| VfsError::NotFound(path.to_path_buf()))
59    }
60
61    fn stamp(&self, path: &Path) -> Result<Stamp, VfsError> {
62        self.files
63            .read()
64            .expect("MemoryVfs lock poisoned")
65            .get(path)
66            .map(|e| Stamp::new(u128::from(e.version), e.contents.len() as u64))
67            .ok_or_else(|| VfsError::NotFound(path.to_path_buf()))
68    }
69
70    fn write(&self, path: &Path, contents: &str) -> Result<(), VfsError> {
71        let entry = self.entry(contents.to_owned());
72        self.files
73            .write()
74            .expect("MemoryVfs lock poisoned")
75            .insert(path.to_path_buf(), entry);
76        Ok(())
77    }
78
79    fn exists(&self, path: &Path) -> bool {
80        self.files
81            .read()
82            .expect("MemoryVfs lock poisoned")
83            .contains_key(path)
84    }
85
86    fn entry_kind(&self, path: &Path) -> Result<Option<EntryKind>, VfsError> {
87        Ok(self.exists(path).then_some(EntryKind::File))
88    }
89
90    fn prepare_parent(&self, _path: &Path) -> ParentCreation {
91        ParentCreation::new(Vec::new(), Ok(()))
92    }
93
94    fn remove_file(&self, path: &Path) -> Result<(), VfsError> {
95        self.files
96            .write()
97            .expect("MemoryVfs lock poisoned")
98            .remove(path)
99            .map(|_| ())
100            .ok_or_else(|| VfsError::NotFound(path.to_path_buf()))
101    }
102
103    fn remove_empty_dir(&self, path: &Path) -> Result<(), VfsError> {
104        Err(VfsError::NotFound(path.to_path_buf()))
105    }
106
107    fn move_if_absent(&self, from: &Path, to: &Path) -> Result<(), MoveError> {
108        let mut files = self.files.write().expect("MemoryVfs lock poisoned");
109        if files.contains_key(to) {
110            return Err(MoveError::new(
111                VfsError::Exists(to.to_path_buf()),
112                MoveState::Unchanged,
113            ));
114        }
115        let moved = files.remove(from).ok_or_else(|| {
116            MoveError::new(VfsError::NotFound(from.to_path_buf()), MoveState::Unchanged)
117        })?;
118        let entry = Entry {
119            contents: moved.contents,
120            version: self.versions.fetch_add(1, Ordering::Relaxed),
121        };
122        files.insert(to.to_path_buf(), entry);
123        Ok(())
124    }
125
126    fn walk(&self, root: &Path) -> Result<Vec<PathBuf>, VfsError> {
127        Ok(self
128            .files
129            .read()
130            .expect("MemoryVfs lock poisoned")
131            .keys()
132            .filter(|path| path.starts_with(root))
133            .cloned()
134            .collect())
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn memory_moves_preserve_occupied_destinations() {
144        let vfs = MemoryVfs::new()
145            .with_file("/ws/a", "source")
146            .with_file("/ws/b", "foreign");
147        let error = vfs
148            .move_if_absent(Path::new("/ws/a"), Path::new("/ws/b"))
149            .unwrap_err();
150        assert_eq!(error.state, MoveState::Unchanged);
151        assert!(matches!(error.source, VfsError::Exists(_)));
152        assert_eq!(vfs.read(Path::new("/ws/a")).unwrap(), "source");
153        assert_eq!(vfs.read(Path::new("/ws/b")).unwrap(), "foreign");
154    }
155
156    #[test]
157    fn walk_is_scoped_and_sorted() {
158        let vfs = MemoryVfs::new()
159            .with_file("/ws/b.rs", "")
160            .with_file("/ws/a.rs", "")
161            .with_file("/other/c.rs", "");
162        let files = vfs.walk(Path::new("/ws")).unwrap();
163        assert_eq!(
164            files,
165            vec![PathBuf::from("/ws/a.rs"), PathBuf::from("/ws/b.rs")]
166        );
167    }
168}