async_hal/io/
read.rs

1use super::AsyncRead;
2use core::{
3    marker::PhantomPinned,
4    pin::Pin,
5    task::{Context, Poll},
6};
7use futures::{ready, Future};
8use pin_project_lite::pin_project;
9
10pin_project! {
11    /// A future which can be used to easily read available number of bytes to fill
12    /// a buffer.
13    ///
14    /// Created by the [`read`] function.
15    #[derive(Debug)]
16    #[must_use = "futures do nothing unless you `.await` or poll them"]
17    pub struct Read<'a, R: ?Sized> {
18        reader: &'a mut R,
19        buf: &'a mut [u8],
20        // Make this future `!Unpin` for compatibility with async trait methods.
21        #[pin]
22        _pin: PhantomPinned,
23    }
24}
25
26impl<'a, R: ?Sized> Read<'a, R> {
27    pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self {
28        Self {
29            reader,
30            buf,
31            _pin: PhantomPinned,
32        }
33    }
34}
35
36impl<R> Future for Read<'_, R>
37where
38    R: AsyncRead + Unpin + ?Sized,
39{
40    type Output = Result<usize, R::Error>;
41
42    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<usize, R::Error>> {
43        let me = self.project();
44
45        let amt = ready!(Pin::new(me.reader).poll_read(cx, me.buf))?;
46        Poll::Ready(Ok(amt))
47    }
48}