Files
tokio/tokio-fs/src/lib.rs
T

91 lines
2.5 KiB
Rust
Raw Normal View History

2018-05-02 11:19:58 -07:00
//! Asynchronous filesystem manipulation operations (and stdin, stdout, stderr).
//!
//! This module contains basic methods and types for manipulating the contents
//! of the local filesystem from within the context of the Tokio runtime.
//!
//! Tasks running on the Tokio runtime are expected to be asynchronous, i.e.,
//! they will not block the thread of execution. Filesystem operations do not
//! satisfy this requirement. In order to perform filesystem operations
//! asynchronously, this library uses the [`blocking`][blocking] annotation
//! to signal to the runtime that a blocking operation is being performed. This
//! allows the runtime to compensate.
//!
//! [blocking]: https://docs.rs/tokio-threadpool/0.1/tokio_threadpool/fn.blocking.html
#![deny(missing_docs, missing_debug_implementations, warnings)]
#![doc(html_root_url = "https://docs.rs/tokio-fs/0.1.1")]
2018-05-02 11:19:58 -07:00
#[macro_use]
extern crate futures;
extern crate tokio_io;
extern crate tokio_threadpool;
pub mod file;
mod stdin;
mod stdout;
mod stderr;
pub use file::File;
2018-06-12 10:47:24 -07:00
pub use file::OpenOptions;
2018-05-02 11:19:58 -07:00
pub use stdin::{stdin, Stdin};
pub use stdout::{stdout, Stdout};
pub use stderr::{stderr, Stderr};
2018-06-20 22:12:06 +02:00
use futures::{Future, Poll};
2018-05-02 11:19:58 -07:00
use futures::Async::*;
2018-06-20 22:12:06 +02:00
use std::fs::{self, Metadata};
2018-05-02 11:19:58 -07:00
use std::io;
use std::io::ErrorKind::{Other, WouldBlock};
2018-06-20 22:12:06 +02:00
use std::path::PathBuf;
/// Queries the file system metadata for a path
pub fn metadata(path: PathBuf) -> MetadataFuture {
MetadataFuture { path }
}
/// Future returned by `metadata`
#[derive(Debug)]
pub struct MetadataFuture {
path: PathBuf,
}
impl Future for MetadataFuture {
type Item = Metadata;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
blocking_io(|| fs::metadata(&self.path))
}
}
2018-05-02 11:19:58 -07:00
fn blocking_io<F, T>(f: F) -> Poll<T, io::Error>
where F: FnOnce() -> io::Result<T>,
{
match tokio_threadpool::blocking(f) {
Ok(Ready(Ok(v))) => Ok(v.into()),
Ok(Ready(Err(err))) => Err(err),
Ok(NotReady) => Ok(NotReady),
Err(_) => Err(blocking_err()),
}
}
fn would_block<F, T>(f: F) -> io::Result<T>
where F: FnOnce() -> io::Result<T>,
{
match tokio_threadpool::blocking(f) {
Ok(Ready(Ok(v))) => Ok(v),
Ok(Ready(Err(err))) => {
debug_assert_ne!(err.kind(), WouldBlock);
Err(err)
}
Ok(NotReady) => Err(WouldBlock.into()),
Err(_) => Err(blocking_err()),
}
}
fn blocking_err() -> io::Error {
io::Error::new(Other, "`blocking` annotated I/O must be called \
2018-05-02 11:19:58 -07:00
from the context of the Tokio runtime.")
}