tokio/io/
async_buf_read.rs

1use crate::io::AsyncRead;
2
3use std::io;
4use std::ops::DerefMut;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7
8/// Reads bytes asynchronously.
9///
10/// This trait is analogous to [`std::io::BufRead`], but integrates with
11/// the asynchronous task system. In particular, the [`poll_fill_buf`] method,
12/// unlike [`BufRead::fill_buf`], will automatically queue the current task for wakeup
13/// and return if data is not yet available, rather than blocking the calling
14/// thread.
15///
16/// Utilities for working with `AsyncBufRead` values are provided by
17/// [`AsyncBufReadExt`].
18///
19/// [`std::io::BufRead`]: std::io::BufRead
20/// [`poll_fill_buf`]: AsyncBufRead::poll_fill_buf
21/// [`BufRead::fill_buf`]: std::io::BufRead::fill_buf
22/// [`AsyncBufReadExt`]: crate::io::AsyncBufReadExt
23pub trait AsyncBufRead: AsyncRead {
24    /// Attempts to return the contents of the internal buffer, filling it with more data
25    /// from the inner reader if it is empty.
26    ///
27    /// On success, returns `Poll::Ready(Ok(buf))`.
28    ///
29    /// If no data is available for reading, the method returns
30    /// `Poll::Pending` and arranges for the current task (via
31    /// `cx.waker().wake_by_ref()`) to receive a notification when the object becomes
32    /// readable or is closed.
33    ///
34    /// This function is a lower-level call. It needs to be paired with the
35    /// [`consume`] method to function properly. When calling this
36    /// method, none of the contents will be "read" in the sense that later
37    /// calling [`poll_read`] may return the same contents. As such, [`consume`] must
38    /// be called with the number of bytes that are consumed from this buffer to
39    /// ensure that the bytes are never returned twice.
40    ///
41    /// An empty buffer returned indicates that the stream has reached EOF.
42    ///
43    /// [`poll_read`]: AsyncRead::poll_read
44    /// [`consume`]: AsyncBufRead::consume
45    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>>;
46
47    /// Tells this buffer that `amt` bytes have been consumed from the buffer,
48    /// so they should no longer be returned in calls to [`poll_read`].
49    ///
50    /// This function is a lower-level call. It needs to be paired with the
51    /// [`poll_fill_buf`] method to function properly. This function does
52    /// not perform any I/O, it simply informs this object that some amount of
53    /// its buffer, returned from [`poll_fill_buf`], has been consumed and should
54    /// no longer be returned. As such, this function may do odd things if
55    /// [`poll_fill_buf`] isn't called before calling it.
56    ///
57    /// The `amt` must be `<=` the number of bytes in the buffer returned by
58    /// [`poll_fill_buf`].
59    ///
60    /// [`poll_read`]: AsyncRead::poll_read
61    /// [`poll_fill_buf`]: AsyncBufRead::poll_fill_buf
62    fn consume(self: Pin<&mut Self>, amt: usize);
63}
64
65macro_rules! deref_async_buf_read {
66    () => {
67        fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
68            Pin::new(&mut **self.get_mut()).poll_fill_buf(cx)
69        }
70
71        fn consume(mut self: Pin<&mut Self>, amt: usize) {
72            Pin::new(&mut **self).consume(amt)
73        }
74    };
75}
76
77impl<T: ?Sized + AsyncBufRead + Unpin> AsyncBufRead for Box<T> {
78    deref_async_buf_read!();
79}
80
81impl<T: ?Sized + AsyncBufRead + Unpin> AsyncBufRead for &mut T {
82    deref_async_buf_read!();
83}
84
85impl<P> AsyncBufRead for Pin<P>
86where
87    P: DerefMut + Unpin,
88    P::Target: AsyncBufRead,
89{
90    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
91        self.get_mut().as_mut().poll_fill_buf(cx)
92    }
93
94    fn consume(self: Pin<&mut Self>, amt: usize) {
95        self.get_mut().as_mut().consume(amt);
96    }
97}
98
99impl AsyncBufRead for &[u8] {
100    fn poll_fill_buf(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
101        Poll::Ready(Ok(*self))
102    }
103
104    fn consume(mut self: Pin<&mut Self>, amt: usize) {
105        *self = &self[amt..];
106    }
107}
108
109impl<T: AsRef<[u8]> + Unpin> AsyncBufRead for io::Cursor<T> {
110    fn poll_fill_buf(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
111        Poll::Ready(io::BufRead::fill_buf(self.get_mut()))
112    }
113
114    fn consume(self: Pin<&mut Self>, amt: usize) {
115        io::BufRead::consume(self.get_mut(), amt);
116    }
117}