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
use std::ffi::OsString;
use std::fs;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Mutex;

use cfg_if::cfg_if;
use futures::future::{self, FutureExt, TryFutureExt};

use crate::future::Future;
use crate::io;
use crate::task::{blocking, Poll};

/// An entry inside a directory.
///
/// An instance of `DirEntry` represents an entry inside a directory on the filesystem. Each entry
/// carriers additional information like the full path or metadata.
///
/// This type is an async version of [`std::fs::DirEntry`].
///
/// [`std::fs::DirEntry`]: https://doc.rust-lang.org/std/fs/struct.DirEntry.html
#[derive(Debug)]
pub struct DirEntry {
    /// The state of the entry.
    state: Mutex<State>,

    /// The full path to the entry.
    path: PathBuf,

    #[cfg(unix)]
    ino: u64,

    /// The bare name of the entry without the leading path.
    file_name: OsString,
}

/// The state of an asynchronous `DirEntry`.
///
/// The `DirEntry` can be either idle or busy performing an asynchronous operation.
#[derive(Debug)]
enum State {
    Idle(Option<fs::DirEntry>),
    Busy(blocking::JoinHandle<State>),
}

impl DirEntry {
    /// Creates an asynchronous `DirEntry` from a synchronous handle.
    pub(crate) fn new(inner: fs::DirEntry) -> DirEntry {
        #[cfg(unix)]
        let dir_entry = DirEntry {
            path: inner.path(),
            file_name: inner.file_name(),
            ino: inner.ino(),
            state: Mutex::new(State::Idle(Some(inner))),
        };

        #[cfg(windows)]
        let dir_entry = DirEntry {
            path: inner.path(),
            file_name: inner.file_name(),
            state: Mutex::new(State::Idle(Some(inner))),
        };

        dir_entry
    }

    /// Returns the full path to this entry.
    ///
    /// The full path is created by joining the original path passed to [`read_dir`] with the name
    /// of this entry.
    ///
    /// [`read_dir`]: fn.read_dir.html
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #![feature(async_await)]
    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
    /// #
    /// use async_std::fs;
    /// use async_std::prelude::*;
    ///
    /// let mut dir = fs::read_dir(".").await?;
    ///
    /// while let Some(entry) = dir.next().await {
    ///     let entry = entry?;
    ///     println!("{:?}", entry.path());
    /// }
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn path(&self) -> PathBuf {
        self.path.clone()
    }

    /// Returns the metadata for this entry.
    ///
    /// This function will not traverse symlinks if this entry points at a symlink.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #![feature(async_await)]
    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
    /// #
    /// use async_std::fs;
    /// use async_std::prelude::*;
    ///
    /// let mut dir = fs::read_dir(".").await?;
    ///
    /// while let Some(entry) = dir.next().await {
    ///     let entry = entry?;
    ///     println!("{:?}", entry.metadata().await?);
    /// }
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn metadata(&self) -> io::Result<fs::Metadata> {
        future::poll_fn(|cx| {
            let state = &mut *self.state.lock().unwrap();

            loop {
                match state {
                    State::Idle(opt) => match opt.take() {
                        None => return Poll::Ready(None),
                        Some(inner) => {
                            let (s, r) = futures::channel::oneshot::channel();

                            // Start the operation asynchronously.
                            *state = State::Busy(blocking::spawn(async move {
                                let res = inner.metadata();
                                let _ = s.send(res);
                                State::Idle(Some(inner))
                            }));

                            return Poll::Ready(Some(r));
                        }
                    },
                    // Poll the asynchronous operation the file is currently blocked on.
                    State::Busy(task) => *state = futures::ready!(Pin::new(task).poll(cx)),
                }
            }
        })
        .map(|opt| opt.ok_or_else(|| io_error("invalid state")))
        .await?
        .map_err(|_| io_error("blocking task failed"))
        .await?
    }

    /// Returns the file type for this entry.
    ///
    /// This function will not traverse symlinks if this entry points at a symlink.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #![feature(async_await)]
    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
    /// #
    /// use async_std::fs;
    /// use async_std::prelude::*;
    ///
    /// let mut dir = fs::read_dir(".").await?;
    ///
    /// while let Some(entry) = dir.next().await {
    ///     let entry = entry?;
    ///     println!("{:?}", entry.file_type().await?);
    /// }
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn file_type(&self) -> io::Result<fs::FileType> {
        future::poll_fn(|cx| {
            let state = &mut *self.state.lock().unwrap();

            loop {
                match state {
                    State::Idle(opt) => match opt.take() {
                        None => return Poll::Ready(None),
                        Some(inner) => {
                            let (s, r) = futures::channel::oneshot::channel();

                            // Start the operation asynchronously.
                            *state = State::Busy(blocking::spawn(async move {
                                let res = inner.file_type();
                                let _ = s.send(res);
                                State::Idle(Some(inner))
                            }));

                            return Poll::Ready(Some(r));
                        }
                    },
                    // Poll the asynchronous operation the file is currently blocked on.
                    State::Busy(task) => *state = futures::ready!(Pin::new(task).poll(cx)),
                }
            }
        })
        .map(|opt| opt.ok_or_else(|| io_error("invalid state")))
        .await?
        .map_err(|_| io_error("blocking task failed"))
        .await?
    }

    /// Returns the bare name of this entry without the leading path.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #![feature(async_await)]
    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
    /// #
    /// use async_std::fs;
    /// use async_std::prelude::*;
    ///
    /// let mut dir = fs::read_dir(".").await?;
    ///
    /// while let Some(entry) = dir.next().await {
    ///     let entry = entry?;
    ///     println!("{:?}", entry.file_name());
    /// }
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn file_name(&self) -> OsString {
        self.file_name.clone()
    }
}

/// Creates a custom `io::Error` with an arbitrary error type.
fn io_error(err: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> io::Error {
    io::Error::new(io::ErrorKind::Other, err)
}

cfg_if! {
    if #[cfg(feature = "docs")] {
        use crate::os::unix::fs::DirEntryExt;
    } else if #[cfg(unix)] {
        use std::os::unix::fs::DirEntryExt;
    }
}

#[cfg_attr(feature = "docs", doc(cfg(unix)))]
cfg_if! {
    if #[cfg(any(unix, feature = "docs"))] {
        impl DirEntryExt for DirEntry {
            fn ino(&self) -> u64 {
                self.ino
            }
        }
    }
}