tokio_stream/wrappers/
read_dir.rs

1use crate::Stream;
2use std::io;
3use std::pin::Pin;
4use std::task::{Context, Poll};
5use tokio::fs::{DirEntry, ReadDir};
6
7/// A wrapper around [`tokio::fs::ReadDir`] that implements [`Stream`].
8///
9/// # Example
10///
11/// ```
12/// use tokio::fs::read_dir;
13/// use tokio_stream::{StreamExt, wrappers::ReadDirStream};
14///
15/// # #[tokio::main(flavor = "current_thread")]
16/// # async fn main() -> std::io::Result<()> {
17/// let dirs = read_dir(".").await?;
18/// let mut dirs = ReadDirStream::new(dirs);
19/// while let Some(dir) = dirs.next().await {
20///     let dir = dir?;
21///     println!("{}", dir.path().display());
22/// }
23/// # Ok(())
24/// # }
25/// ```
26///
27/// [`tokio::fs::ReadDir`]: struct@tokio::fs::ReadDir
28/// [`Stream`]: trait@crate::Stream
29#[derive(Debug)]
30#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
31pub struct ReadDirStream {
32    inner: ReadDir,
33}
34
35impl ReadDirStream {
36    /// Create a new `ReadDirStream`.
37    pub fn new(read_dir: ReadDir) -> Self {
38        Self { inner: read_dir }
39    }
40
41    /// Get back the inner `ReadDir`.
42    pub fn into_inner(self) -> ReadDir {
43        self.inner
44    }
45}
46
47impl Stream for ReadDirStream {
48    type Item = io::Result<DirEntry>;
49
50    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
51        self.inner.poll_next_entry(cx).map(Result::transpose)
52    }
53}
54
55impl AsRef<ReadDir> for ReadDirStream {
56    fn as_ref(&self) -> &ReadDir {
57        &self.inner
58    }
59}
60
61impl AsMut<ReadDir> for ReadDirStream {
62    fn as_mut(&mut self) -> &mut ReadDir {
63        &mut self.inner
64    }
65}