d-major 0.0.0

Traverse directory trees in parallel, using relative entries to minimize allocation and maximize parallelism.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/*
 * Description: OS filesystem abstraction.
 *
 * Copyright (C) 2025 d@nny mc² <dmc2@hypnicjerk.ai>
 * SPDX-License-Identifier: LGPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

//! OS filesystem abstraction.

pub mod traits {
  #[cfg(doc)]
  use std::{
    fs, io,
    path::{Path, PathBuf},
  };


  #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
  pub enum FileType {
    File,
    Dir,
    Link,
  }

  pub trait Stat {
    type Mode;
    fn file_type(&self) -> Result<FileType, Self::Mode>;
  }

  pub trait DirectoryEntry {
    type PathRef<'s>;
    type OwnedPath;

    fn name<'e>(&'e self) -> Self::PathRef<'e>;
    fn owned_name(path: Self::PathRef<'_>) -> Self::OwnedPath;

    /// This is different from the type used for [`Stat::Mode`], as POSIX directory entries do not
    /// contain a full stat struct but instead a specific field with its own values to parse.
    type EagerMode;

    /// Some platforms have this in the directory entry, while some require an additional stat call.
    fn eager_file_type(&self) -> Option<Result<FileType, Self::EagerMode>>;
  }

  pub trait DirectoryStream {
    /// A single result from a directory stream, like [`fs::DirEntry`].
    type DirEntry<'dir>: DirectoryEntry
    where Self: 'dir;
    /// Result type which is either [`io::Error`] or wraps it.
    type Err;

    fn read_dir<'dir>(&'dir mut self) -> Result<Option<Self::DirEntry<'dir>>, Self::Err>;
  }

  pub trait VFS {
    /// Can be thought of as essentially a [`PathBuf`], but in practice forms a trie.
    type Ctx<'vfs>
    where Self: 'vfs;
    /// Result type which is either [`io::Error`] or wraps it.
    type Err;

    /// Convertible from a null-terminated C string, especially
    /// [`MeasuredNullTermStr`](crate::null_term_str::MeasuredNullTermStr).
    type PathRef<'s>;
    /// Convertible from an owned null-terminated C string, especially
    /// [`NullTermString`](crate::null_term_str::NullTermString).
    type OwnedPath;
    fn path_ref<'s>(p: &'s Self::OwnedPath) -> Self::PathRef<'s>;

    /// This will return a context representing the process's current working directory.
    fn initial_context<'vfs>(&'vfs self) -> Result<Self::Ctx<'vfs>, Self::Err>;
    fn join_context_dir<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Self::Ctx<'vfs>;
    fn join_context_link<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      link_rel: Self::PathRef<'_>,
      target: Self::PathRef<'_>,
    ) -> Self::Ctx<'vfs>;

    /// Convertible from e.g. [`libc::stat64`].
    ///
    /// Contains a file type without needing to perform another syscall.
    type Stat: Stat;

    /// Convertible from e.g. [`fs::File`].
    type File;
    /// Typically just [`fs::OpenOptions`].
    type FileOptions;

    /// An open directory stream, like the result of [`fs::read_dir()`].
    type Dir<'vfs>: DirectoryStream
    where Self: 'vfs;
    fn entry_rel<'vfs, 'dir, 's>(
      name: <<<Self as VFS>::Dir<'vfs> as DirectoryStream>::DirEntry<'dir> as DirectoryEntry>::PathRef<'s>,
    ) -> Self::PathRef<'s>;
    fn entry_owned_rel<'vfs, 'dir>(
      name: <<<Self as VFS>::Dir<'vfs> as DirectoryStream>::DirEntry<'dir> as DirectoryEntry>::OwnedPath,
    ) -> Self::OwnedPath;

    /// Read metadata from a file path and/or directory entry.
    fn stat<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Result<Self::Stat, Self::Err>;

    /// Read the contents of a symbolic link.
    fn read_link<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Result<Self::OwnedPath, Self::Err>;

    /// Open a file handle.
    ///
    /// While this crate is for directory crawling, opening files increases open file descriptor
    /// count, so we must manage it along with our directory traversal.
    fn open_file<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
      opts: Self::FileOptions,
    ) -> Result<Self::File, Self::Err>;

    /// Open a directory stream.
    fn open_dir<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Result<Self::Dir<'vfs>, Self::Err>;
  }
}


#[cfg(unix)]
pub mod posix {}

pub mod path_based {
  use std::{
    env, ffi, fs, io,
    path::{Path, PathBuf},
  };

  use super::traits;

  #[derive(Debug, Clone)]
  #[repr(transparent)]
  pub struct Stat(fs::Metadata);

  impl traits::Stat for Stat {
    type Mode = fs::FileType;
    fn file_type(&self) -> Result<traits::FileType, Self::Mode> {
      let ty = self.0.file_type();
      if ty.is_symlink() {
        return Ok(traits::FileType::Link);
      }
      if ty.is_file() {
        return Ok(traits::FileType::File);
      }
      if ty.is_dir() {
        return Ok(traits::FileType::Dir);
      }
      Err(ty)
    }
  }

  cfg_if::cfg_if! {
    if #[cfg(all(unix, feature = "nightly"))] {
      #[derive(Debug)]
      #[repr(transparent)]
      pub struct DirectoryEntry(fs::DirEntry);

      impl DirectoryEntry {
        pub fn new(entry: fs::DirEntry) -> Self { Self(entry) }
      }

      impl traits::DirectoryEntry for DirectoryEntry {
        type PathRef<'s> = &'s ffi::OsStr;
        type OwnedPath = ffi::OsString;

        fn name<'e>(&'e self) -> Self::PathRef<'e> {
          use std::os::unix::fs::DirEntryExt2;
          self.0.file_name_ref()
        }
        fn owned_name(path: Self::PathRef<'_>) -> Self::OwnedPath {
          path.to_os_string()
        }

        type EagerMode = fs::FileType;

        cfg_if::cfg_if! {
          if #[cfg(any(
            target_os = "solaris",
            target_os = "illumos",
            target_os = "haiku",
            target_os = "vxworks",
            target_os = "aix",
            target_os = "nto",
            target_os = "vita",
          ))] {
            fn eager_file_type(&self) -> Option<Result<traits::FileType, Self::EagerMode>> { None }
          } else {
            fn eager_file_type(&self) -> Option<Result<traits::FileType, Self::EagerMode>> {
              let ty = self.0.file_type().unwrap();
              if ty.is_symlink() {
                return Some(Ok(traits::FileType::Link));
              }
              if ty.is_file() {
                return Some(Ok(traits::FileType::File));
              }
              if ty.is_dir() {
                return Some(Ok(traits::FileType::Dir));
              }
              Some(Err(ty))
            }
          }
        }
      }
    } else {
      #[derive(Debug)]
      pub struct DirectoryEntry {
        inner: fs::DirEntry,
        name: ffi::OsString,
      }

      impl DirectoryEntry {
        pub fn new(entry: fs::DirEntry) -> Self {
          let name = entry.file_name();
          Self {
            inner: entry,
            name,
          }
        }
      }

      impl traits::DirectoryEntry for DirectoryEntry {
        type PathRef<'s> = &'s ffi::OsStr;
        type OwnedPath = ffi::OsString;

        fn name<'e>(&'e self) -> Self::PathRef<'e> {
          &self.name
        }
        fn owned_name(path: Self::PathRef<'_>) -> Self::OwnedPath {
          path.to_os_string()
        }

        type EagerMode = fs::FileType;

        cfg_if::cfg_if! {
          if #[cfg(any(
            target_os = "solaris",
            target_os = "illumos",
            target_os = "haiku",
            target_os = "vxworks",
            target_os = "aix",
            target_os = "nto",
            target_os = "vita",
          ))] {
            fn eager_file_type(&self) -> Option<Result<traits::FileType, Self::EagerMode>> { None }
          } else {
            fn eager_file_type(&self) -> Option<Result<traits::FileType, Self::EagerMode>> {
              let ty = self.inner.file_type().unwrap();
              if ty.is_symlink() {
                return Some(Ok(traits::FileType::Link));
              }
              if ty.is_file() {
                return Some(Ok(traits::FileType::File));
              }
              if ty.is_dir() {
                return Some(Ok(traits::FileType::Dir));
              }
              Some(Err(ty))
            }
          }
        }
      }
    }
  }

  pub struct DirectoryStream {
    inner: fs::ReadDir,
    done: bool,
  }

  impl traits::DirectoryStream for DirectoryStream {
    type DirEntry<'dir> = DirectoryEntry;
    type Err = io::Error;

    fn read_dir<'dir>(&'dir mut self) -> Result<Option<Self::DirEntry<'dir>>, Self::Err> {
      if self.done {
        return Ok(None);
      }

      loop {
        use traits::DirectoryEntry as _;

        let Some(result) = self.inner.next().transpose()? else {
          self.done = true;
          return Ok(None);
        };
        let entry = DirectoryEntry::new(result);
        let name = entry.name();
        if name == "." || name == ".." {
          continue;
        }
        return Ok(Some(entry));
      }
    }
  }

  #[derive(Debug)]
  pub struct VFS;

  impl traits::VFS for VFS {
    type Ctx<'vfs> = PathBuf;
    type Err = io::Error;

    type PathRef<'s> = &'s Path;
    type OwnedPath = PathBuf;
    fn path_ref<'s>(p: &'s Self::OwnedPath) -> Self::PathRef<'s> { p.as_ref() }

    fn initial_context<'vfs>(&'vfs self) -> Result<Self::Ctx<'vfs>, Self::Err> {
      env::current_dir()
    }
    fn join_context_dir<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Self::Ctx<'vfs> {
      ctx.join(rel)
    }
    fn join_context_link<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      _link_rel: Self::PathRef<'_>,
      target: Self::PathRef<'_>,
    ) -> Self::Ctx<'vfs> {
      ctx.join(target)
    }

    type Stat = Stat;

    type File = fs::File;
    type FileOptions = fs::OpenOptions;

    type Dir<'vfs> = DirectoryStream;
    fn entry_rel<'vfs, 'dir, 's>(
      name: <<<Self as traits::VFS>::Dir<'vfs> as traits::DirectoryStream>::DirEntry<'dir> as traits::DirectoryEntry>::PathRef<'s>,
    ) -> Self::PathRef<'s> {
      name.as_ref()
    }
    fn entry_owned_rel<'vfs, 'dir>(
      name: <<<Self as traits::VFS>::Dir<'vfs> as traits::DirectoryStream>::DirEntry<'dir> as traits::DirectoryEntry>::OwnedPath,
    ) -> Self::OwnedPath {
      name.into()
    }

    fn stat<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Result<Self::Stat, Self::Err> {
      fs::symlink_metadata(ctx.join(rel)).map(Stat)
    }

    fn read_link<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Result<Self::OwnedPath, Self::Err> {
      fs::read_link(ctx.join(rel))
    }

    fn open_file<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
      opts: Self::FileOptions,
    ) -> Result<Self::File, Self::Err> {
      opts.open(ctx.join(rel))
    }

    /* FIXME: handle max fd count here too!!!! */
    fn open_dir<'vfs>(
      &'vfs self,
      ctx: Self::Ctx<'vfs>,
      rel: Self::PathRef<'_>,
    ) -> Result<Self::Dir<'vfs>, Self::Err> {
      fs::read_dir(ctx.join(rel)).map(|inner| DirectoryStream { inner, done: false })
    }
  }

  #[cfg(test)]
  mod test {
    use tempdir::TempDir;

    use super::*;


    #[test]
    fn file() -> io::Result<()> {
      let td = TempDir::new("asdf")?;
      fs::write(td.path().join("f.txt"), "asdf\n")?;

      use traits::VFS as _;
      let vfs = VFS;
      let ctx = vfs.initial_context()?;
      let ctx = vfs.join_context_dir(ctx, td.path());

      use traits::Stat as _;
      let stat = vfs.stat(ctx.clone(), Path::new("f.txt"))?;
      assert_eq!(stat.file_type(), Ok(traits::FileType::File));

      let mut opts = fs::OpenOptions::new();
      opts.read(true);
      let mut f = vfs.open_file(ctx, Path::new("f.txt"), opts)?;

      use io::Read;
      let mut s = String::new();
      f.read_to_string(&mut s)?;
      assert_eq!(s, "asdf\n");

      Ok(())
    }

    #[test]
    fn link() -> io::Result<()> {
      let td = TempDir::new("asdf")?;
      cfg_if::cfg_if! {
        if #[cfg(unix)] {
          std::os::unix::fs::symlink("wow.txt", td.path().join("l.txt"))?;
        } else {
          std::os::windows::fs::symlink_file("wow.txt", td.path().join("l.txt"))?;
        }
      }

      use traits::VFS as _;
      let vfs = VFS;
      let ctx = vfs.initial_context()?;
      let ctx = vfs.join_context_dir(ctx, td.path());

      use traits::Stat as _;
      let stat = vfs.stat(ctx.clone(), Path::new("l.txt"))?;
      assert_eq!(stat.file_type(), Ok(traits::FileType::Link));

      let target = vfs.read_link(ctx, Path::new("l.txt"))?;
      assert_eq!(&target, Path::new("wow.txt"));

      Ok(())
    }

    #[test]
    fn dir() -> io::Result<()> {
      let td = TempDir::new("asdf")?;
      fs::write(td.path().join("f.txt"), "asdf\n")?;
      fs::create_dir(td.path().join("a"))?;
      fs::write(td.path().join("a/g.txt"), "asdf2\n")?;
      /* FIXME: test symlink context with VFS::join_context_link()! */

      use traits::VFS as _;
      let vfs = VFS;
      let ctx = vfs.initial_context()?;

      use traits::Stat as _;
      let stat = vfs.stat(ctx.clone(), td.path())?;
      assert_eq!(stat.file_type(), Ok(traits::FileType::Dir));

      let mut opts = fs::OpenOptions::new();
      opts.read(true);

      use io::Read;
      use traits::{DirectoryEntry as _, DirectoryStream as _, Stat as _};
      let mut dir = vfs.open_dir(ctx.clone(), td.path())?;
      let ctx = vfs.join_context_dir(ctx, td.path());
      while let Some(entry) = dir.read_dir()? {
        let ty = entry
          .eager_file_type()
          .map(|r| r.unwrap())
          .unwrap_or_else(|| {
            vfs
              .stat(ctx.clone(), VFS::entry_rel(entry.name()))
              .unwrap()
              .file_type()
              .unwrap()
          });
        match VFS::path_ref(&VFS::entry_owned_rel(DirectoryEntry::owned_name(
          entry.name(),
        )))
        .to_str()
        .unwrap()
        {
          "f.txt" => {
            assert_eq!(ty, traits::FileType::File);
            let mut f = vfs.open_file(ctx.clone(), VFS::entry_rel(entry.name()), opts.clone())?;
            let mut s = String::new();
            f.read_to_string(&mut s)?;
            assert_eq!(s, "asdf\n");
          },
          "a" => {
            assert_eq!(ty, traits::FileType::Dir);

            let mut dir = vfs.open_dir(ctx.clone(), VFS::entry_rel(entry.name()))?;
            let ctx = vfs.join_context_dir(ctx.clone(), VFS::entry_rel(entry.name()));
            while let Some(entry) = dir.read_dir()? {
              let ty = entry
                .eager_file_type()
                .map(|r| r.unwrap())
                .unwrap_or_else(|| {
                  vfs
                    .stat(ctx.clone(), VFS::entry_rel(entry.name()))
                    .unwrap()
                    .file_type()
                    .unwrap()
                });
              match DirectoryEntry::owned_name(entry.name()).to_str().unwrap() {
                "g.txt" => {
                  assert_eq!(ty, traits::FileType::File);
                  let mut f =
                    vfs.open_file(ctx.clone(), VFS::entry_rel(entry.name()), opts.clone())?;
                  let mut s = String::new();
                  f.read_to_string(&mut s)?;
                  assert_eq!(s, "asdf2\n");
                },
                _ => unreachable!(),
              }
            }
          },
          _ => unreachable!(),
        }
      }

      Ok(())
    }
  }
}