Skip to main content

lensbench_core/
vfs.rs

1//! ファイルの読み書きの入口。読み書きは今の計算のファイルの口([`Fs`])を通す。既定はネイティブなら
2//! `std::fs` そのまま([`StdFs`])、wasm(ブラウザ)にはファイルシステムが無いのでプロセスの中のファイル置き場
3//! ([`MemFs`]、見本の系・ガラス・利用者が読み込んだファイルは [`insert`] で入れてから、ネイティブと同じパスで読む)。
4//! [`with`] で計算ごとに別の口(メモリの上の [`MemFs`] など)を渡せる: 文字列から系を組む・試験で偽のファイルを
5//! 渡す、がディスクに触らずにできる。口は計算の文脈([`crate::par::Ctx`])に載り、並列の作業のスレッドにも効く。
6//!
7//! 系・カタログ・膜・マクロなど、利用者のファイルを読む・書く所は `std::fs` ではなくこれを通す
8//! (テストと、ネイティブでしか動かない機能(serve・run など)はそのままでよい)。
9
10use std::io;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14/// ファイルの読み書きの口([`with`] で計算ごとに渡す)。パスはネイティブと同じ形で受ける
15pub trait Fs: Send + Sync {
16    fn read(&self, p: &Path) -> io::Result<Vec<u8>>;
17    /// 書く(あれば置き換える)
18    fn write(&self, p: &Path, b: &[u8]) -> io::Result<()>;
19    /// 書く(途中で落ちても前か新しい中身のどちらかが残る)。既定は [`Fs::write`]
20    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    /// フォルダの中のファイル・フォルダのパス(並びは決まっていない)
27    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    /// 更新の印(読み直しの判定用)
32    fn stamp(&self, p: &Path) -> io::Result<Stamp>;
33    fn canonicalize(&self, p: &Path) -> io::Result<PathBuf>;
34}
35
36/// ファイルの更新の印(読み直しの判定用): 更新時刻(分かれば)と大きさ
37pub 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    /// 同じフォルダの一時ファイルに書いてから名前を変える(書く途中で落ちても元のファイルは残る)。
47    /// 書き先がシンボリックリンクならリンクの先を置き換え、普通のファイルでないもの(/dev/stdout・名前付きパイプなど)
48    /// には直接書く(置き換えると壊す)
49    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/// ネイティブのファイルシステム(`std::fs`)
146#[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/// メモリの上のファイル置き場(パス → 中身)。wasm の既定の口で、ネイティブでも [`with`] で渡せる
190/// (試験の偽のファイル・文字列から組む系)。パスは `/` 区切りの絶対パスに揃える(相対パスは `/` から)
191#[derive(Default)]
192pub struct MemFs {
193    inner: std::sync::Mutex<MemInner>,
194}
195
196/// パス → 中身と版(書くたびに増やす。読み直しの判定に使う)、消したファイル(パス → 消したときの版)
197#[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    /// 次の版。版の数はプロセスで 1 つ(どの置き場でも増えるだけ): 別の置き場の同じパス・同じ大きさのファイルの
206    /// stamp が重ならず、stamp で読込を使い回す所(glass::load_agf_shared など)が前の置き場の中身を返さない
207    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    /// 書いた版(消した印を外す)
214    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    /// 消す(消した印を付ける)
221    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
236/// `.`・`..`・重なった `/` を畳んだ絶対パス(相対パスは `/` から)
237fn 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    /// いまの版(これより後の変更を [`MemFs::changes_since`] が返す)
276    pub fn seq(&self) -> u64 {
277        self.lock().ver
278    }
279
280    /// 版 seq より後に書いた・消したファイル(パス、中身(消したら None)、版)
281    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    /// 別の置き場の変更を当てる(中身が None なら消す)。当てた後の版
299    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    /// 置き場のファイルの一覧(パスと大きさ)
309    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        // フォルダはファイルのパスから決まる(空のフォルダは持たない)
363        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        // 時刻の代わりに版を使う(同じ大きさで書き直しても読み直す。秒にするのは Windows の SystemTime が 100 ns 刻みのため)
387        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/// wasm のプロセスの置き場(ブラウザにはこれしかファイルの置き場がない)
400#[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
406/// プロセスの既定の口(ネイティブは [`StdFs`]、wasm はプロセスの置き場の [`MemFs`])
407pub 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
417/// 今の計算の口([`with`] で渡したもの、無ければ [`default_fs`])
418pub fn current() -> Arc<dyn Fs> {
419    crate::par::current_fs().unwrap_or_else(default_fs)
420}
421
422/// f をファイルの口 fs の下で回す(文脈のほかの項目は引き継ぐ。並列の作業のスレッドにも効く)
423pub fn with<R>(fs: Arc<dyn Fs>, f: impl FnOnce() -> R) -> R {
424    crate::par::with_fs(fs, f)
425}
426
427thread_local! {
428    /// [`recording`] の間にこのスレッドで読んだファイル・フォルダ
429    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
441/// [`recording`] で得たパス paths を、このスレッドの記録に足す(並列の作業のスレッドで記録した分を、呼び出した
442/// スレッドの記録へ戻すのに使う。記録していなければ何もしない)
443pub fn record(paths: &[PathBuf]) {
444    for p in paths {
445        note(p);
446    }
447}
448
449/// f を呼び、その間にこのスレッドで [`read`]・[`read_dir`] で開いた(開こうとした)パスを並べて返す(読み直しの
450/// 判定に使う。カタログの一覧が参照する、見ているフォルダの外のファイル)。ほかのスレッドで読んだものは
451/// 入らない(f の中で並列に読むなら、作業のスレッドごとに recording で取って [`record`] で戻す)。入れ子にすると内側の分は外側にも入る
452pub 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
467/// ファイルの中身
468pub fn read(p: impl AsRef<Path>) -> io::Result<Vec<u8>> {
469    note(p.as_ref());
470    current().read(p.as_ref())
471}
472
473/// UTF-8 のテキストとして読む
474pub 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
478/// 書く(あれば置き換える)
479pub fn write(p: impl AsRef<Path>, b: impl AsRef<[u8]>) -> io::Result<()> {
480    current().write(p.as_ref(), b.as_ref())
481}
482
483/// 書く(あれば置き換える)。途中で落ちても前の中身か新しい中身のどちらかが残るように、同じフォルダの
484/// 一時ファイルに書いて `sync_all` してから名前を替える。カタログ・系ファイルなど作り直しのきかないものの保存に
485pub 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
489/// 末尾に足す(無ければ作る)
490pub 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
506/// フォルダの中のファイル・フォルダのパス(並びは決まっていない)
507pub 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
520/// 名前を変える(置き換え先があれば置き換える)
521pub fn rename(a: impl AsRef<Path>, b: impl AsRef<Path>) -> io::Result<()> {
522    current().rename(a.as_ref(), b.as_ref())
523}
524
525/// 更新の印(更新時刻と大きさ)
526pub 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
534/// 一時ファイルのフォルダ(ネイティブは `std::env::temp_dir`、wasm は置き場の `/tmp`。wasm の
535/// `std::env::temp_dir` は panic する)
536pub 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
543/// 置き場にファイルを入れる(wasm 用。ネイティブでは [`write`] と同じ)
544pub fn insert(p: impl AsRef<Path>, b: impl AsRef<[u8]>) -> io::Result<()> {
545    write(p, b)
546}
547
548/// プロセスの置き場のファイルの一覧(パスと大きさ)。wasm だけ
549#[cfg(target_arch = "wasm32")]
550pub fn files() -> Vec<(PathBuf, u64)> {
551    wasm_store().files()
552}
553
554/// プロセスの置き場を別の置き場(Web Worker の中の wasm)へ写す。wasm だけ
555#[cfg(target_arch = "wasm32")]
556pub mod sync {
557    /// いまの版
558    pub fn seq() -> u64 {
559        super::wasm_store().seq()
560    }
561    /// 版 seq より後に書いた・消したファイル
562    pub fn changes_since(seq: u64) -> Vec<(String, Option<Vec<u8>>, u64)> {
563        super::wasm_store().changes_since(seq)
564    }
565    /// 別の置き場の変更を当てる
566    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    /// 保存は一時ファイルから名前を変える: 上書きでき、一時ファイルは残らない
577    #[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        // シンボリックリンクはリンクの先を書き換え、リンクは残す
593        #[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            // 普通のファイルでない書き先(/dev/null)は置き換えずに直接書く
604            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        // 同じ大きさで書き直しても印が変わる
630        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        // 別の置き場へ写す変更: 書いたものと消したもの
640        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    /// 書き替えは一時ファイルを残さず、前の中身を置き換える
665    #[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}