1use std::io;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14pub trait Fs: Send + Sync {
16 fn read(&self, p: &Path) -> io::Result<Vec<u8>>;
17 fn write(&self, p: &Path, b: &[u8]) -> io::Result<()>;
19 fn write_atomic(&self, p: &Path, b: &[u8]) -> io::Result<()> {
21 self.write(p, b)
22 }
23 fn append(&self, p: &Path, b: &[u8]) -> io::Result<()>;
24 fn is_file(&self, p: &Path) -> bool;
25 fn is_dir(&self, p: &Path) -> bool;
26 fn read_dir(&self, p: &Path) -> io::Result<Vec<PathBuf>>;
28 fn create_dir_all(&self, p: &Path) -> io::Result<()>;
29 fn remove_file(&self, p: &Path) -> io::Result<()>;
30 fn rename(&self, a: &Path, b: &Path) -> io::Result<()>;
31 fn stamp(&self, p: &Path) -> io::Result<Stamp>;
33 fn canonicalize(&self, p: &Path) -> io::Result<PathBuf>;
34}
35
36pub type Stamp = (Option<std::time::SystemTime>, u64);
38
39#[cfg(not(target_arch = "wasm32"))]
40mod imp {
41 use super::*;
42
43 pub(super) fn read(p: &Path) -> io::Result<Vec<u8>> {
44 std::fs::read(p)
45 }
46 pub(super) fn write(p: &Path, b: &[u8]) -> io::Result<()> {
50 use std::io::Write;
51 let resolved;
52 let p = match std::fs::metadata(p) {
53 Ok(m) if !m.is_file() => return std::fs::write(p, b),
54 Ok(_) if std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_symlink()) => {
55 resolved = std::fs::canonicalize(p)?;
56 resolved.as_path()
57 }
58 _ => p,
59 };
60 use std::sync::atomic::{AtomicU64, Ordering};
61 static SEQ: AtomicU64 = AtomicU64::new(0);
62 let name = p
63 .file_name()
64 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name"))?;
65 let mut tmp_name = std::ffi::OsString::from(".");
66 tmp_name.push(name);
67 tmp_name.push(format!(
68 ".{}-{}.tmp",
69 std::process::id(),
70 SEQ.fetch_add(1, Ordering::Relaxed)
71 ));
72 let tmp = p.with_file_name(tmp_name);
73 let res = (|| {
74 let mut f = std::fs::File::create(&tmp)?;
75 f.write_all(b)?;
76 f.sync_all()?;
77 drop(f);
78 std::fs::rename(&tmp, p)
79 })();
80 if res.is_err() {
81 let _ = std::fs::remove_file(&tmp);
82 }
83 res
84 }
85 pub(super) fn write_atomic(p: &Path, b: &[u8]) -> io::Result<()> {
86 use std::io::Write;
87 let dir = match p.parent() {
88 Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(),
89 _ => PathBuf::from("."),
90 };
91 let name = p
92 .file_name()
93 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name"))?;
94 let mut tmp_name = std::ffi::OsString::from(".");
95 tmp_name.push(name);
96 tmp_name.push(format!(".{}.tmp", std::process::id()));
97 let tmp = dir.join(tmp_name);
98 let r = (|| {
99 let mut f = std::fs::File::create(&tmp)?;
100 f.write_all(b)?;
101 f.sync_all()?;
102 drop(f);
103 std::fs::rename(&tmp, p)
104 })();
105 if r.is_err() {
106 let _ = std::fs::remove_file(&tmp);
107 }
108 r
109 }
110 pub(super) fn append(p: &Path, b: &[u8]) -> io::Result<()> {
111 use std::io::Write;
112 std::fs::OpenOptions::new()
113 .append(true)
114 .create(true)
115 .open(p)?
116 .write_all(b)
117 }
118 pub(super) fn is_file(p: &Path) -> bool {
119 p.is_file()
120 }
121 pub(super) fn is_dir(p: &Path) -> bool {
122 p.is_dir()
123 }
124 pub(super) fn read_dir(p: &Path) -> io::Result<Vec<PathBuf>> {
125 std::fs::read_dir(p)?.map(|e| e.map(|e| e.path())).collect()
126 }
127 pub(super) fn create_dir_all(p: &Path) -> io::Result<()> {
128 std::fs::create_dir_all(p)
129 }
130 pub(super) fn remove_file(p: &Path) -> io::Result<()> {
131 std::fs::remove_file(p)
132 }
133 pub(super) fn rename(a: &Path, b: &Path) -> io::Result<()> {
134 std::fs::rename(a, b)
135 }
136 pub(super) fn stamp(p: &Path) -> io::Result<Stamp> {
137 let m = std::fs::metadata(p)?;
138 Ok((m.modified().ok(), m.len()))
139 }
140 pub(super) fn canonicalize(p: &Path) -> io::Result<PathBuf> {
141 std::fs::canonicalize(p)
142 }
143}
144
145#[cfg(not(target_arch = "wasm32"))]
147pub struct StdFs;
148
149#[cfg(not(target_arch = "wasm32"))]
150impl Fs for StdFs {
151 fn read(&self, p: &Path) -> io::Result<Vec<u8>> {
152 imp::read(p)
153 }
154 fn write(&self, p: &Path, b: &[u8]) -> io::Result<()> {
155 imp::write(p, b)
156 }
157 fn write_atomic(&self, p: &Path, b: &[u8]) -> io::Result<()> {
158 imp::write_atomic(p, b)
159 }
160 fn append(&self, p: &Path, b: &[u8]) -> io::Result<()> {
161 imp::append(p, b)
162 }
163 fn is_file(&self, p: &Path) -> bool {
164 imp::is_file(p)
165 }
166 fn is_dir(&self, p: &Path) -> bool {
167 imp::is_dir(p)
168 }
169 fn read_dir(&self, p: &Path) -> io::Result<Vec<PathBuf>> {
170 imp::read_dir(p)
171 }
172 fn create_dir_all(&self, p: &Path) -> io::Result<()> {
173 imp::create_dir_all(p)
174 }
175 fn remove_file(&self, p: &Path) -> io::Result<()> {
176 imp::remove_file(p)
177 }
178 fn rename(&self, a: &Path, b: &Path) -> io::Result<()> {
179 imp::rename(a, b)
180 }
181 fn stamp(&self, p: &Path) -> io::Result<Stamp> {
182 imp::stamp(p)
183 }
184 fn canonicalize(&self, p: &Path) -> io::Result<PathBuf> {
185 imp::canonicalize(p)
186 }
187}
188
189#[derive(Default)]
192pub struct MemFs {
193 inner: std::sync::Mutex<MemInner>,
194}
195
196#[derive(Default)]
198struct MemInner {
199 store: std::collections::BTreeMap<String, (Vec<u8>, u64)>,
200 removed: std::collections::BTreeMap<String, u64>,
201 ver: u64,
202}
203
204impl MemInner {
205 fn next(&mut self) -> u64 {
208 use std::sync::atomic::{AtomicU64, Ordering};
209 static VER: AtomicU64 = AtomicU64::new(0);
210 self.ver = VER.fetch_add(1, Ordering::Relaxed) + 1;
211 self.ver
212 }
213 fn put(&mut self, k: String, b: Vec<u8>) -> u64 {
215 let v = self.next();
216 self.removed.remove(&k);
217 self.store.insert(k, (b, v));
218 v
219 }
220 fn drop_key(&mut self, k: &str) -> Option<u64> {
222 self.store.remove(k)?;
223 let v = self.next();
224 self.removed.insert(k.to_string(), v);
225 Some(v)
226 }
227 fn is_dir(&self, k: &str) -> bool {
228 let pre = dir_prefix(k);
229 self.store
230 .range(pre.clone()..)
231 .next()
232 .is_some_and(|(f, _)| f.starts_with(&pre))
233 }
234}
235
236fn mem_key(p: &Path) -> String {
238 let mut parts: Vec<String> = Vec::new();
239 for c in p.to_string_lossy().replace('\\', "/").split('/') {
240 match c {
241 "" | "." => {}
242 ".." => {
243 parts.pop();
244 }
245 c => parts.push(c.to_string()),
246 }
247 }
248 format!("/{}", parts.join("/"))
249}
250
251fn dir_prefix(k: &str) -> String {
252 if k == "/" {
253 k.to_string()
254 } else {
255 format!("{k}/")
256 }
257}
258
259fn not_found(p: &Path) -> io::Error {
260 io::Error::new(
261 io::ErrorKind::NotFound,
262 format!("{}: no such file", p.display()),
263 )
264}
265
266impl MemFs {
267 pub fn new() -> Self {
268 Self::default()
269 }
270
271 fn lock(&self) -> std::sync::MutexGuard<'_, MemInner> {
272 self.inner.lock().unwrap_or_else(|e| e.into_inner())
273 }
274
275 pub fn seq(&self) -> u64 {
277 self.lock().ver
278 }
279
280 pub fn changes_since(&self, seq: u64) -> Vec<(String, Option<Vec<u8>>, u64)> {
282 let g = self.lock();
283 let mut out: Vec<(String, Option<Vec<u8>>, u64)> = g
284 .store
285 .iter()
286 .filter(|(_, (_, v))| *v > seq)
287 .map(|(k, (b, v))| (k.clone(), Some(b.clone()), *v))
288 .collect();
289 out.extend(
290 g.removed
291 .iter()
292 .filter(|(_, v)| **v > seq)
293 .map(|(k, v)| (k.clone(), None, *v)),
294 );
295 out
296 }
297
298 pub fn apply(&self, k: &str, b: Option<Vec<u8>>) -> u64 {
300 let k = mem_key(Path::new(k));
301 let mut g = self.lock();
302 match b {
303 Some(b) => g.put(k, b),
304 None => g.drop_key(&k).unwrap_or(g.ver),
305 }
306 }
307
308 pub fn files(&self) -> Vec<(PathBuf, u64)> {
310 self.lock()
311 .store
312 .iter()
313 .map(|(k, (b, _))| (PathBuf::from(k), b.len() as u64))
314 .collect()
315 }
316}
317
318impl Fs for MemFs {
319 fn read(&self, p: &Path) -> io::Result<Vec<u8>> {
320 self.lock()
321 .store
322 .get(&mem_key(p))
323 .map(|x| x.0.clone())
324 .ok_or_else(|| not_found(p))
325 }
326 fn write(&self, p: &Path, b: &[u8]) -> io::Result<()> {
327 self.lock().put(mem_key(p), b.to_vec());
328 Ok(())
329 }
330 fn append(&self, p: &Path, b: &[u8]) -> io::Result<()> {
331 let k = mem_key(p);
332 let mut g = self.lock();
333 let mut x = g.store.get(&k).map(|e| e.0.clone()).unwrap_or_default();
334 x.extend_from_slice(b);
335 g.put(k, x);
336 Ok(())
337 }
338 fn is_file(&self, p: &Path) -> bool {
339 self.lock().store.contains_key(&mem_key(p))
340 }
341 fn is_dir(&self, p: &Path) -> bool {
342 self.lock().is_dir(&mem_key(p))
343 }
344 fn read_dir(&self, p: &Path) -> io::Result<Vec<PathBuf>> {
345 let k = mem_key(p);
346 let g = self.lock();
347 if !g.is_dir(&k) {
348 return Err(not_found(p));
349 }
350 let pre = dir_prefix(&k);
351 let mut out: Vec<PathBuf> = Vec::new();
352 for f in g.store.keys().filter(|f| f.starts_with(&pre)) {
353 let first = f[pre.len()..].split('/').next().unwrap_or("");
354 let q = PathBuf::from(format!("{pre}{first}"));
355 if out.last() != Some(&q) {
356 out.push(q);
357 }
358 }
359 Ok(out)
360 }
361 fn create_dir_all(&self, _p: &Path) -> io::Result<()> {
362 Ok(())
364 }
365 fn remove_file(&self, p: &Path) -> io::Result<()> {
366 self.lock()
367 .drop_key(&mem_key(p))
368 .map(|_| ())
369 .ok_or_else(|| not_found(p))
370 }
371 fn rename(&self, a: &Path, b: &Path) -> io::Result<()> {
372 let mut g = self.lock();
373 let ka = mem_key(a);
374 let x = g
375 .store
376 .get(&ka)
377 .map(|e| e.0.clone())
378 .ok_or_else(|| not_found(a))?;
379 g.drop_key(&ka);
380 g.put(mem_key(b), x);
381 Ok(())
382 }
383 fn stamp(&self, p: &Path) -> io::Result<Stamp> {
384 let g = self.lock();
385 let (b, v) = g.store.get(&mem_key(p)).ok_or_else(|| not_found(p))?;
386 let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(*v);
388 Ok((Some(t), b.len() as u64))
389 }
390 fn canonicalize(&self, p: &Path) -> io::Result<PathBuf> {
391 if self.is_file(p) || self.is_dir(p) {
392 Ok(PathBuf::from(mem_key(p)))
393 } else {
394 Err(not_found(p))
395 }
396 }
397}
398
399#[cfg(target_arch = "wasm32")]
401fn wasm_store() -> &'static Arc<MemFs> {
402 static S: std::sync::OnceLock<Arc<MemFs>> = std::sync::OnceLock::new();
403 S.get_or_init(Default::default)
404}
405
406pub fn default_fs() -> Arc<dyn Fs> {
408 #[cfg(target_arch = "wasm32")]
409 return wasm_store().clone();
410 #[cfg(not(target_arch = "wasm32"))]
411 {
412 static S: std::sync::OnceLock<Arc<dyn Fs>> = std::sync::OnceLock::new();
413 S.get_or_init(|| Arc::new(StdFs)).clone()
414 }
415}
416
417pub fn current() -> Arc<dyn Fs> {
419 crate::par::current_fs().unwrap_or_else(default_fs)
420}
421
422pub fn with<R>(fs: Arc<dyn Fs>, f: impl FnOnce() -> R) -> R {
424 crate::par::with_fs(fs, f)
425}
426
427thread_local! {
428 static RECORD: std::cell::RefCell<Option<std::collections::BTreeSet<PathBuf>>> =
430 const { std::cell::RefCell::new(None) };
431}
432
433fn note(p: &Path) {
434 RECORD.with(|r| {
435 if let Some(s) = r.borrow_mut().as_mut() {
436 s.insert(p.to_path_buf());
437 }
438 });
439}
440
441pub fn record(paths: &[PathBuf]) {
444 for p in paths {
445 note(p);
446 }
447}
448
449pub fn recording<R>(f: impl FnOnce() -> R) -> (R, Vec<PathBuf>) {
453 let outer = RECORD.with(|r| r.borrow_mut().replace(Default::default()));
454 let res = f();
455 let got = RECORD.with(|r| {
456 let mut g = r.borrow_mut();
457 let got = g.take().unwrap_or_default();
458 if let Some(mut o) = outer {
459 o.extend(got.iter().cloned());
460 *g = Some(o);
461 }
462 got
463 });
464 (res, got.into_iter().collect())
465}
466
467pub fn read(p: impl AsRef<Path>) -> io::Result<Vec<u8>> {
469 note(p.as_ref());
470 current().read(p.as_ref())
471}
472
473pub fn read_to_string(p: impl AsRef<Path>) -> io::Result<String> {
475 String::from_utf8(read(p)?).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
476}
477
478pub fn write(p: impl AsRef<Path>, b: impl AsRef<[u8]>) -> io::Result<()> {
480 current().write(p.as_ref(), b.as_ref())
481}
482
483pub fn write_atomic(p: impl AsRef<Path>, b: impl AsRef<[u8]>) -> io::Result<()> {
486 current().write_atomic(p.as_ref(), b.as_ref())
487}
488
489pub fn append(p: impl AsRef<Path>, b: impl AsRef<[u8]>) -> io::Result<()> {
491 current().append(p.as_ref(), b.as_ref())
492}
493
494pub fn exists(p: impl AsRef<Path>) -> bool {
495 is_file(&p) || is_dir(&p)
496}
497
498pub fn is_file(p: impl AsRef<Path>) -> bool {
499 current().is_file(p.as_ref())
500}
501
502pub fn is_dir(p: impl AsRef<Path>) -> bool {
503 current().is_dir(p.as_ref())
504}
505
506pub fn read_dir(p: impl AsRef<Path>) -> io::Result<Vec<PathBuf>> {
508 note(p.as_ref());
509 current().read_dir(p.as_ref())
510}
511
512pub fn create_dir_all(p: impl AsRef<Path>) -> io::Result<()> {
513 current().create_dir_all(p.as_ref())
514}
515
516pub fn remove_file(p: impl AsRef<Path>) -> io::Result<()> {
517 current().remove_file(p.as_ref())
518}
519
520pub fn rename(a: impl AsRef<Path>, b: impl AsRef<Path>) -> io::Result<()> {
522 current().rename(a.as_ref(), b.as_ref())
523}
524
525pub fn stamp(p: impl AsRef<Path>) -> io::Result<Stamp> {
527 current().stamp(p.as_ref())
528}
529
530pub fn canonicalize(p: impl AsRef<Path>) -> io::Result<PathBuf> {
531 current().canonicalize(p.as_ref())
532}
533
534pub fn temp_dir() -> PathBuf {
537 #[cfg(target_arch = "wasm32")]
538 return PathBuf::from("/tmp");
539 #[cfg(not(target_arch = "wasm32"))]
540 std::env::temp_dir()
541}
542
543pub fn insert(p: impl AsRef<Path>, b: impl AsRef<[u8]>) -> io::Result<()> {
545 write(p, b)
546}
547
548#[cfg(target_arch = "wasm32")]
550pub fn files() -> Vec<(PathBuf, u64)> {
551 wasm_store().files()
552}
553
554#[cfg(target_arch = "wasm32")]
556pub mod sync {
557 pub fn seq() -> u64 {
559 super::wasm_store().seq()
560 }
561 pub fn changes_since(seq: u64) -> Vec<(String, Option<Vec<u8>>, u64)> {
563 super::wasm_store().changes_since(seq)
564 }
565 pub fn apply(k: &str, b: Option<Vec<u8>>) -> u64 {
567 super::wasm_store().apply(k, b)
568 }
569}
570
571#[cfg(test)]
572mod tests {
573 use super::{Fs, MemFs};
574 use std::path::{Path, PathBuf};
575
576 #[cfg(not(target_arch = "wasm32"))]
578 #[test]
579 fn native_write_is_atomic_replace() {
580 let d = std::env::temp_dir().join(format!("lb-vfs-atomic-{}", std::process::id()));
581 std::fs::create_dir_all(&d).unwrap();
582 let p = d.join("a.zmx");
583 super::imp::write(&p, b"old").unwrap();
584 super::imp::write(&p, b"new").unwrap();
585 assert_eq!(std::fs::read(&p).unwrap(), b"new");
586 let names: Vec<_> = std::fs::read_dir(&d)
587 .unwrap()
588 .map(|e| e.unwrap().file_name())
589 .collect();
590 assert_eq!(names.len(), 1, "{names:?}");
591 assert!(super::imp::write(&d.join("no/such/dir.zmx"), b"x").is_err());
592 #[cfg(unix)]
594 {
595 let link = d.join("link.zmx");
596 std::os::unix::fs::symlink(&p, &link).unwrap();
597 super::imp::write(&link, b"via link").unwrap();
598 assert!(std::fs::symlink_metadata(&link)
599 .unwrap()
600 .file_type()
601 .is_symlink());
602 assert_eq!(std::fs::read(&p).unwrap(), b"via link");
603 super::imp::write(Path::new("/dev/null"), b"x").unwrap();
605 assert!(!std::fs::metadata("/dev/null").unwrap().is_file());
606 }
607 let _ = std::fs::remove_dir_all(&d);
608 }
609
610 #[test]
611 fn memory_store_reads_lists_and_stamps() {
612 let mem = MemFs::new();
613 let d = Path::new("/vfs-test");
614 mem.write(&d.join("a/x.agf"), b"1").unwrap();
615 mem.write(&d.join("a/./b/../y.agf"), b"22").unwrap();
616 mem.write(Path::new("\\vfs-test\\a\\sub\\z.zmx"), b"3")
617 .unwrap();
618 assert_eq!(mem.read(&d.join("a/y.agf")).unwrap(), b"22");
619 assert!(mem.is_dir(&d.join("a")) && mem.is_dir(d) && !mem.is_dir(&d.join("a/x.agf")));
620 assert!(mem.is_file(&d.join("a/x.agf")) && !mem.is_file(&d.join("a")));
621 let mut l = mem.read_dir(&d.join("a")).unwrap();
622 l.sort();
623 let want: Vec<PathBuf> = ["/vfs-test/a/sub", "/vfs-test/a/x.agf", "/vfs-test/a/y.agf"]
624 .iter()
625 .map(PathBuf::from)
626 .collect();
627 assert_eq!(l, want);
628 assert!(mem.read_dir(&d.join("none")).is_err());
629 let s0 = mem.stamp(&d.join("a/x.agf")).unwrap();
631 mem.write(&d.join("a/x.agf"), b"9").unwrap();
632 assert_ne!(mem.stamp(&d.join("a/x.agf")).unwrap(), s0);
633 mem.append(&d.join("a/x.agf"), b"8").unwrap();
634 assert_eq!(mem.read(&d.join("a/x.agf")).unwrap(), b"98");
635 mem.rename(&d.join("a/x.agf"), &d.join("a/w.agf")).unwrap();
636 assert!(mem.read(&d.join("a/x.agf")).is_err());
637 assert_eq!(mem.read(&d.join("a/w.agf")).unwrap(), b"98");
638 mem.rename(&d.join("a/w.agf"), &d.join("a/x.agf")).unwrap();
639 let s0 = mem.seq();
641 mem.remove_file(&d.join("a/x.agf")).unwrap();
642 mem.write(&d.join("a/new.agf"), b"n").unwrap();
643 let mut ch: Vec<(String, Option<Vec<u8>>)> = mem
644 .changes_since(s0)
645 .into_iter()
646 .filter(|c| c.0.starts_with("/vfs-test/"))
647 .map(|c| (c.0, c.1))
648 .collect();
649 ch.sort();
650 assert_eq!(
651 ch,
652 vec![
653 ("/vfs-test/a/new.agf".to_string(), Some(b"n".to_vec())),
654 ("/vfs-test/a/x.agf".to_string(), None),
655 ]
656 );
657 assert!(mem.changes_since(mem.seq()).is_empty());
658 mem.apply("/vfs-test/a/x.agf", Some(b"r".to_vec()));
659 assert_eq!(mem.read(&d.join("a/x.agf")).unwrap(), b"r");
660 mem.apply("/vfs-test/a/x.agf", None);
661 assert!(mem.read(&d.join("a/x.agf")).is_err());
662 }
663
664 #[cfg(not(target_arch = "wasm32"))]
666 #[test]
667 fn write_atomic_replaces() {
668 let d = std::env::temp_dir().join(format!("lb-vfs-write-atomic-{}", std::process::id()));
669 std::fs::create_dir_all(&d).unwrap();
670 let p = d.join("cat.json");
671 super::write_atomic(&p, "a").unwrap();
672 super::write_atomic(&p, "bb").unwrap();
673 assert_eq!(std::fs::read_to_string(&p).unwrap(), "bb");
674 assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1);
675 std::fs::remove_dir_all(&d).unwrap();
676 }
677}