futures_util/io/
read.rs

1use std::io;
2use std::mem;
3
4use {Future, Poll, task};
5
6use io::AsyncRead;
7
8#[derive(Debug)]
9enum State<R, T> {
10    Pending {
11        rd: R,
12        buf: T,
13    },
14    Empty,
15}
16
17pub fn read<R, T>(rd: R, buf: T) -> Read<R, T>
18    where R: AsyncRead,
19          T: AsMut<[u8]>
20{
21    Read { state: State::Pending { rd, buf } }
22}
23
24/// A future which can be used to easily read available number of bytes to fill
25/// a buffer.
26///
27/// Created by the [`read`] function.
28#[derive(Debug)]
29pub struct Read<R, T> {
30    state: State<R, T>,
31}
32
33impl<R, T> Future for Read<R, T>
34    where R: AsyncRead,
35          T: AsMut<[u8]>
36{
37    type Item = (R, T, usize);
38    type Error = io::Error;
39
40    fn poll(&mut self, cx: &mut task::Context) -> Poll<(R, T, usize), io::Error> {
41        let nread = match self.state {
42            State::Pending { ref mut rd, ref mut buf } =>
43                try_ready!(rd.poll_read(cx, &mut buf.as_mut()[..])),
44            State::Empty => panic!("poll a Read after it's done"),
45        };
46
47        match mem::replace(&mut self.state, State::Empty) {
48            State::Pending { rd, buf } => Ok((rd, buf, nread).into()),
49            State::Empty => panic!("invalid internal state"),
50        }
51    }
52}