maybe_fut/api/fs/
read_dir.rs

1use super::DirEntry;
2
3#[derive(Debug, Unwrap)]
4#[unwrap_types(
5    std(std::fs::ReadDir),
6    tokio(tokio::fs::ReadDir),
7    tokio_gated("tokio-fs")
8)]
9/// Reads the entries in a directory.
10///
11/// This struct is returned from the [`super::read_dir`] function of this module and will yield instances of [`DirEntry`].
12/// Through a [`DirEntry`] information like the entry’s path and possibly other metadata can be learned.
13pub struct ReadDir(ReadDirInner);
14
15/// Inner pointer to sync or async read dir.
16#[derive(Debug)]
17#[allow(clippy::large_enum_variant)]
18enum ReadDirInner {
19    /// Std variant of file <https://docs.rs/rustc-std-workspace-std/latest/std/fs/struct.ReadDir.html>
20    Std(std::fs::ReadDir),
21    #[cfg(tokio_fs)]
22    #[cfg_attr(docsrs, doc(cfg(feature = "tokio-fs")))]
23    /// Tokio variant of file <https://docs.rs/tokio/latest/tokio/fs/struct.ReadDir.html>
24    Tokio(tokio::fs::ReadDir),
25}
26
27impl From<std::fs::ReadDir> for ReadDir {
28    fn from(inner: std::fs::ReadDir) -> Self {
29        Self(ReadDirInner::Std(inner))
30    }
31}
32
33#[cfg(tokio_fs)]
34#[cfg_attr(docsrs, doc(cfg(feature = "tokio-fs")))]
35impl From<tokio::fs::ReadDir> for ReadDir {
36    fn from(inner: tokio::fs::ReadDir) -> Self {
37        Self(ReadDirInner::Tokio(inner))
38    }
39}
40
41impl ReadDir {
42    /// Returns the next entry in the directory stream.
43    pub async fn next_entry(&mut self) -> std::io::Result<Option<DirEntry>> {
44        match &mut self.0 {
45            ReadDirInner::Std(inner) => inner
46                .next()
47                .map(|entry| entry.map(DirEntry::from))
48                .transpose(),
49            #[cfg(tokio_fs)]
50            #[cfg_attr(docsrs, doc(cfg(feature = "tokio-fs")))]
51            ReadDirInner::Tokio(inner) => {
52                inner.next_entry().await.map(|res| res.map(DirEntry::from))
53            }
54        }
55    }
56}