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

89 lines
2.8 KiB
Rust
Raw Normal View History

2019-05-14 10:27:36 -07:00
use crate::{file, File};
2019-07-11 11:05:49 -05:00
use std::future::Future;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
2019-02-20 23:38:49 +01:00
use std::{io, mem, path::Path};
use tokio_io;
2019-07-11 11:05:49 -05:00
use tokio_io::AsyncRead;
2019-02-20 23:38:49 +01:00
/// Creates a future which will open a file for reading and read the entire
/// contents into a buffer and return said buffer.
///
/// This is the async equivalent of `std::fs::read`.
///
/// # Examples
///
/// ```no_run
/// use tokio::prelude::Future;
2019-05-14 10:27:36 -07:00
///
/// let task = tokio::fs::read("foo.txt").map(|data| {
/// // do something with the contents of the file ...
/// println!("foo.txt contains {} bytes", data.len());
/// }).map_err(|e| {
/// // handle errors
/// eprintln!("IO error: {:?}", e);
/// });
///
/// tokio::run(task);
2019-02-20 23:38:49 +01:00
/// ```
pub fn read<P>(path: P) -> ReadFile<P>
where
2019-07-11 11:05:49 -05:00
P: AsRef<Path> + Send + Unpin + 'static,
2019-02-20 23:38:49 +01:00
{
ReadFile {
state: State::Open(File::open(path)),
}
}
/// A future used to open a file and read its entire contents into a buffer.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
2019-07-11 11:05:49 -05:00
pub struct ReadFile<P: AsRef<Path> + Send + Unpin + 'static> {
2019-02-20 23:38:49 +01:00
state: State<P>,
}
#[derive(Debug)]
2019-07-11 11:05:49 -05:00
enum State<P: AsRef<Path> + Send + Unpin + 'static> {
2019-02-20 23:38:49 +01:00
Open(file::OpenFuture<P>),
Metadata(file::MetadataFuture),
2019-07-11 11:05:49 -05:00
Reading(Vec<u8>, usize, File),
Empty,
2019-02-20 23:38:49 +01:00
}
2019-07-11 11:05:49 -05:00
impl<P: AsRef<Path> + Send + Unpin + 'static> Future for ReadFile<P> {
type Output = io::Result<Vec<u8>>;
2019-02-20 23:38:49 +01:00
2019-07-11 11:05:49 -05:00
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let inner = Pin::get_mut(self);
match &mut inner.state {
2019-02-20 23:38:49 +01:00
State::Open(ref mut open_file) => {
2019-07-11 11:05:49 -05:00
let file = ready!(Pin::new(open_file).poll(cx))?;
let new_state = State::Metadata(file.metadata());
mem::replace(&mut inner.state, new_state);
Pin::new(inner).poll(cx)
2019-02-20 23:38:49 +01:00
}
State::Metadata(read_metadata) => {
2019-07-11 11:05:49 -05:00
let (file, metadata) = ready!(Pin::new(read_metadata).poll(cx))?;
2019-02-20 23:38:49 +01:00
let buf = Vec::with_capacity(metadata.len() as usize + 1);
2019-07-11 11:05:49 -05:00
let new_state = State::Reading(buf, 0, file);
mem::replace(&mut inner.state, new_state);
Pin::new(inner).poll(cx)
2019-02-20 23:38:49 +01:00
}
2019-07-11 11:05:49 -05:00
State::Reading(buf, ref mut pos, file) => {
let n = ready!(Pin::new(file).poll_read_buf(cx, buf))?;
*pos += n;
if *pos >= buf.len() {
match mem::replace(&mut inner.state, State::Empty) {
State::Reading(buf, _, _) => Poll::Ready(Ok(buf)),
_ => panic!(),
}
} else {
Poll::Pending
}
2019-02-20 23:38:49 +01:00
}
2019-07-11 11:05:49 -05:00
State::Empty => panic!("poll a WriteFile after it's done"),
}
2019-02-20 23:38:49 +01:00
}
}