1use std::collections::{BTreeMap, BTreeSet};
25use std::fmt;
26use std::io::{self, Read as _};
27use std::path::{Component, Path, PathBuf};
28use std::sync::Arc;
29use std::time::SystemTime;
30
31#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct DirItem {
34 pub name: String,
35 pub is_dir: bool,
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct Meta {
41 pub is_dir: bool,
42 pub len: u64,
44 pub modified: Option<SystemTime>,
46}
47
48pub trait FileSystem: Send + Sync + fmt::Debug {
50 fn read_dir(&self, dir: &Path) -> io::Result<Vec<DirItem>>;
52
53 fn metadata(&self, path: &Path) -> io::Result<Meta>;
55
56 fn read(&self, path: &Path, limit: usize) -> io::Result<Vec<u8>>;
58
59 fn can_create_dirs(&self) -> bool {
62 false
63 }
64
65 fn create_dir(&self, _path: &Path) -> io::Result<()> {
67 Err(io::Error::new(
68 io::ErrorKind::Unsupported,
69 "this file system cannot make folders",
70 ))
71 }
72
73 fn is_native(&self) -> bool {
76 false
77 }
78
79 fn is_dir(&self, path: &Path) -> bool {
80 self.metadata(path).is_ok_and(|m| m.is_dir)
81 }
82
83 fn is_file(&self, path: &Path) -> bool {
84 self.metadata(path).is_ok_and(|m| !m.is_dir)
85 }
86}
87
88pub type SharedFs = Arc<dyn FileSystem>;
90
91pub fn native() -> SharedFs {
93 Arc::new(StdFs)
94}
95
96#[derive(Clone, Copy, Debug, Default)]
98pub struct StdFs;
99
100impl FileSystem for StdFs {
101 fn read_dir(&self, dir: &Path) -> io::Result<Vec<DirItem>> {
102 Ok(std::fs::read_dir(dir)?
103 .filter_map(Result::ok)
104 .map(|e| DirItem {
105 name: e.file_name().to_string_lossy().into_owned(),
106 is_dir: e.path().is_dir(),
108 })
109 .collect())
110 }
111
112 fn metadata(&self, path: &Path) -> io::Result<Meta> {
113 let m = std::fs::metadata(path)?;
114 Ok(Meta {
115 is_dir: m.is_dir(),
116 len: if m.is_dir() { 0 } else { m.len() },
117 modified: m.modified().ok(),
118 })
119 }
120
121 fn read(&self, path: &Path, limit: usize) -> io::Result<Vec<u8>> {
122 let mut out = Vec::new();
123 std::fs::File::open(path)?
124 .take(limit as u64)
125 .read_to_end(&mut out)?;
126 Ok(out)
127 }
128
129 fn can_create_dirs(&self) -> bool {
130 !cfg!(target_arch = "wasm32")
132 }
133
134 fn create_dir(&self, path: &Path) -> io::Result<()> {
135 std::fs::create_dir(path)
136 }
137
138 fn is_native(&self) -> bool {
139 true
140 }
141}
142
143#[derive(Clone, Default)]
146pub struct MemoryFs {
147 files: BTreeMap<PathBuf, (Arc<[u8]>, Option<SystemTime>)>,
148 dirs: BTreeSet<PathBuf>,
149}
150
151impl fmt::Debug for MemoryFs {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 f.debug_struct("MemoryFs")
154 .field("files", &self.files.len())
155 .field("dirs", &self.dirs.len())
156 .finish()
157 }
158}
159
160fn normal(path: &Path) -> PathBuf {
162 let mut out = PathBuf::new();
163 for c in path.components() {
164 match c {
165 Component::CurDir => {}
166 Component::ParentDir => {
167 out.pop();
168 }
169 c => out.push(c),
170 }
171 }
172 out
173}
174
175impl MemoryFs {
176 pub fn new() -> Self {
177 Self::default()
178 }
179
180 pub fn dir(mut self, path: impl AsRef<Path>) -> Self {
182 self.add_dir(&normal(path.as_ref()));
183 self
184 }
185
186 pub fn file(self, path: impl AsRef<Path>, bytes: Vec<u8>) -> Self {
188 self.file_at(path, bytes, None)
189 }
190
191 pub fn file_at(
193 mut self,
194 path: impl AsRef<Path>,
195 bytes: Vec<u8>,
196 modified: Option<SystemTime>,
197 ) -> Self {
198 let path = normal(path.as_ref());
199 if let Some(parent) = path.parent() {
200 self.add_dir(parent);
201 }
202 self.files.insert(path, (bytes.into(), modified));
203 self
204 }
205
206 fn add_dir(&mut self, dir: &Path) {
207 for a in dir.ancestors() {
208 if a.as_os_str().is_empty() || !self.dirs.insert(a.to_path_buf()) {
209 break;
210 }
211 }
212 }
213}
214
215impl FileSystem for MemoryFs {
216 fn read_dir(&self, dir: &Path) -> io::Result<Vec<DirItem>> {
217 let dir = normal(dir);
218 if !self.dirs.contains(&dir) {
219 return Err(io::Error::new(io::ErrorKind::NotFound, "no such folder"));
220 }
221 let child = |p: &PathBuf| {
222 (p.parent() == Some(dir.as_path()))
223 .then(|| p.file_name().map(|n| n.to_string_lossy().into_owned()))
224 .flatten()
225 };
226 let dirs = self
227 .dirs
228 .iter()
229 .filter_map(|d| child(d).map(|name| DirItem { name, is_dir: true }));
230 let files = self.files.keys().filter_map(|f| {
231 child(f).map(|name| DirItem {
232 name,
233 is_dir: false,
234 })
235 });
236 Ok(dirs.chain(files).collect())
237 }
238
239 fn metadata(&self, path: &Path) -> io::Result<Meta> {
240 let path = normal(path);
241 if let Some((bytes, modified)) = self.files.get(&path) {
242 return Ok(Meta {
243 is_dir: false,
244 len: bytes.len() as u64,
245 modified: *modified,
246 });
247 }
248 if self.dirs.contains(&path) {
249 return Ok(Meta {
250 is_dir: true,
251 len: 0,
252 modified: None,
253 });
254 }
255 Err(io::Error::new(io::ErrorKind::NotFound, "no such file"))
256 }
257
258 fn read(&self, path: &Path, limit: usize) -> io::Result<Vec<u8>> {
259 let (bytes, _) = self
260 .files
261 .get(&normal(path))
262 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such file"))?;
263 Ok(bytes[..bytes.len().min(limit)].to_vec())
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[test]
272 fn a_memory_folder_lists_reads_and_resolves() {
273 let fs = MemoryFs::new()
274 .file("/r/a/x.txt", b"abc".to_vec())
275 .dir("/r/b/c");
276 let mut names: Vec<_> = fs
277 .read_dir(Path::new("/r"))
278 .unwrap()
279 .into_iter()
280 .map(|e| (e.name, e.is_dir))
281 .collect();
282 names.sort();
283 assert_eq!(names, [("a".into(), true), ("b".into(), true)]);
284 assert!(fs.is_dir(Path::new("/r/b/../a")));
285 assert!(fs.is_file(Path::new("/r/a/./x.txt")));
286 assert_eq!(fs.read(Path::new("/r/a/x.txt"), 99).unwrap(), b"abc");
287 assert!(fs.read_dir(Path::new("/r/a/x.txt")).is_err());
288 assert!(fs.metadata(Path::new("/nope")).is_err());
289 assert!(!fs.is_native());
290 assert!(!fs.can_create_dirs());
292 assert_eq!(
293 fs.create_dir(Path::new("/r/new")).unwrap_err().kind(),
294 io::ErrorKind::Unsupported
295 );
296 assert!(!fs.is_dir(Path::new("/r/new")));
297 }
298}