tokio/io/async_read.rs
1use super::ReadBuf;
2use std::io;
3use std::ops::DerefMut;
4use std::pin::Pin;
5use std::task::{Context, Poll};
6
7/// Reads bytes from a source.
8///
9/// This trait is analogous to the [`std::io::Read`] trait, but integrates with
10/// the asynchronous task system. In particular, the [`poll_read`] method,
11/// unlike [`Read::read`], will automatically queue the current task for wakeup
12/// and return if data is not yet available, rather than blocking the calling
13/// thread.
14///
15/// Specifically, this means that the `poll_read` function will return one of
16/// the following:
17///
18/// * `Poll::Ready(Ok(()))` means that data was immediately read and placed into
19/// the output buffer. The amount of data read can be determined by the
20/// increase in the length of the slice returned by `ReadBuf::filled`. If the
21/// difference is 0, either EOF has been reached, or the output buffer had zero
22/// capacity (i.e. `buf.remaining()` == 0).
23///
24/// * `Poll::Pending` means that no data was read into the buffer
25/// provided. The I/O object is not currently readable but may become readable
26/// in the future. Most importantly, **the current future's task is scheduled
27/// to get unparked when the object is readable**. This means that like
28/// `Future::poll` you'll receive a notification when the I/O object is
29/// readable again.
30///
31/// * `Poll::Ready(Err(e))` for other errors are standard I/O errors coming from the
32/// underlying object.
33///
34/// This trait importantly means that the `read` method only works in the
35/// context of a future's task. The object may panic if used outside of a task.
36///
37/// Utilities for working with `AsyncRead` values are provided by
38/// [`AsyncReadExt`].
39///
40/// [`poll_read`]: AsyncRead::poll_read
41/// [`std::io::Read`]: std::io::Read
42/// [`Read::read`]: std::io::Read::read
43/// [`AsyncReadExt`]: crate::io::AsyncReadExt
44pub trait AsyncRead {
45 /// Attempts to read from the `AsyncRead` into `buf`.
46 ///
47 /// On success, returns `Poll::Ready(Ok(()))` and places data in the
48 /// unfilled portion of `buf`. If no data was read (`buf.filled().len()` is
49 /// unchanged), it implies that EOF has been reached, or the output buffer
50 /// had zero capacity (i.e. `buf.remaining()` == 0).
51 ///
52 /// If no data is available for reading, the method returns `Poll::Pending`
53 /// and arranges for the current task (via `cx.waker()`) to receive a
54 /// notification when the object becomes readable or is closed.
55 fn poll_read(
56 self: Pin<&mut Self>,
57 cx: &mut Context<'_>,
58 buf: &mut ReadBuf<'_>,
59 ) -> Poll<io::Result<()>>;
60}
61
62macro_rules! deref_async_read {
63 () => {
64 fn poll_read(
65 mut self: Pin<&mut Self>,
66 cx: &mut Context<'_>,
67 buf: &mut ReadBuf<'_>,
68 ) -> Poll<io::Result<()>> {
69 Pin::new(&mut **self).poll_read(cx, buf)
70 }
71 };
72}
73
74impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for Box<T> {
75 deref_async_read!();
76}
77
78impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for &mut T {
79 deref_async_read!();
80}
81
82impl<P> AsyncRead for Pin<P>
83where
84 P: DerefMut,
85 P::Target: AsyncRead,
86{
87 fn poll_read(
88 self: Pin<&mut Self>,
89 cx: &mut Context<'_>,
90 buf: &mut ReadBuf<'_>,
91 ) -> Poll<io::Result<()>> {
92 crate::util::pin_as_deref_mut(self).poll_read(cx, buf)
93 }
94}
95
96impl AsyncRead for &[u8] {
97 fn poll_read(
98 mut self: Pin<&mut Self>,
99 _cx: &mut Context<'_>,
100 buf: &mut ReadBuf<'_>,
101 ) -> Poll<io::Result<()>> {
102 let amt = std::cmp::min(self.len(), buf.remaining());
103 let (a, b) = self.split_at(amt);
104 buf.put_slice(a);
105 *self = b;
106 Poll::Ready(Ok(()))
107 }
108}
109
110impl<T: AsRef<[u8]> + Unpin> AsyncRead for io::Cursor<T> {
111 fn poll_read(
112 mut self: Pin<&mut Self>,
113 _cx: &mut Context<'_>,
114 buf: &mut ReadBuf<'_>,
115 ) -> Poll<io::Result<()>> {
116 let pos = self.position();
117 let slice: &[u8] = (*self).get_ref().as_ref();
118
119 // The position could technically be out of bounds, so don't panic...
120 if pos > slice.len() as u64 {
121 return Poll::Ready(Ok(()));
122 }
123
124 let start = pos as usize;
125 let amt = std::cmp::min(slice.len() - start, buf.remaining());
126 // Add won't overflow because of pos check above.
127 let end = start + amt;
128 buf.put_slice(&slice[start..end]);
129 self.set_position(end as u64);
130
131 Poll::Ready(Ok(()))
132 }
133}