cap_primitives/fs/
read_dir.rs

1use crate::fs::{DirEntry, FollowSymlinks, ReadDirInner};
2use std::path::Path;
3use std::{fmt, fs, io};
4
5/// Construct a `ReadDir` to iterate over the contents of a directory,
6/// ensuring that the resolution of the path never escapes the directory
7/// tree rooted at `start`.
8#[inline]
9pub fn read_dir(start: &fs::File, path: &Path) -> io::Result<ReadDir> {
10    Ok(ReadDir {
11        inner: ReadDirInner::new(start, path, FollowSymlinks::Yes)?,
12    })
13}
14
15/// Like `read_dir`, but fails if `path` names a symlink.
16#[inline]
17#[cfg(not(windows))]
18pub(crate) fn read_dir_nofollow(start: &fs::File, path: &Path) -> io::Result<ReadDir> {
19    Ok(ReadDir {
20        inner: ReadDirInner::new(start, path, FollowSymlinks::No)?,
21    })
22}
23
24/// Like `read_dir` but operates on the base directory itself, rather than
25/// on a path based on it.
26#[inline]
27pub fn read_base_dir(start: &fs::File) -> io::Result<ReadDir> {
28    Ok(ReadDir {
29        inner: ReadDirInner::read_base_dir(start)?,
30    })
31}
32
33/// Like `read_dir`, but doesn't perform sandboxing.
34#[inline]
35#[cfg(not(windows))]
36pub(crate) fn read_dir_unchecked(
37    start: &fs::File,
38    path: &Path,
39    follow: FollowSymlinks,
40) -> io::Result<ReadDir> {
41    Ok(ReadDir {
42        inner: ReadDirInner::new_unchecked(start, path, follow)?,
43    })
44}
45
46/// Iterator over the entries in a directory.
47///
48/// This corresponds to [`std::fs::ReadDir`].
49///
50/// There is no `from_std` method, as `std::fs::ReadDir` doesn't provide a way
51/// to construct a `ReadDir` without opening directories by ambient paths.
52pub struct ReadDir {
53    pub(crate) inner: ReadDirInner,
54}
55
56impl Iterator for ReadDir {
57    type Item = io::Result<DirEntry>;
58
59    #[inline]
60    fn next(&mut self) -> Option<Self::Item> {
61        self.inner
62            .next()
63            .map(|inner| inner.map(|inner| DirEntry { inner }))
64    }
65}
66
67impl fmt::Debug for ReadDir {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        self.inner.fmt(f)
70    }
71}