async_hal/io/
async_buf_read.rs

1use super::AsyncRead;
2use core::{
3    pin::Pin,
4    task::{Context, Poll},
5};
6
7pub trait AsyncBufRead: AsyncRead {
8    /// Attempts to return the contents of the internal buffer, filling it with more data
9    /// from the inner reader if it is empty.
10    ///
11    /// On success, returns `Poll::Ready(Ok(buf))`.
12    ///
13    /// If no data is available for reading, the method returns
14    /// `Poll::Pending` and arranges for the current task (via
15    /// `cx.waker().wake_by_ref()`) to receive a notification when the object becomes
16    /// readable or is closed.
17    ///
18    /// This function is a lower-level call. It needs to be paired with the
19    /// [`consume`] method to function properly. When calling this
20    /// method, none of the contents will be "read" in the sense that later
21    /// calling [`poll_read`] may return the same contents. As such, [`consume`] must
22    /// be called with the number of bytes that are consumed from this buffer to
23    /// ensure that the bytes are never returned twice.
24    ///
25    /// An empty buffer returned indicates that the stream has reached EOF.
26    ///
27    /// [`poll_read`]: AsyncRead::poll_read
28    /// [`consume`]: AsyncBufRead::consume
29    fn poll_fill_buf(
30        self: Pin<&mut Self>,
31        cx: &mut Context<'_>,
32    ) -> Poll<Result<&[u8], Self::Error>>;
33
34    /// Tells this buffer that `amt` bytes have been consumed from the buffer,
35    /// so they should no longer be returned in calls to [`poll_read`].
36    ///
37    /// This function is a lower-level call. It needs to be paired with the
38    /// [`poll_fill_buf`] method to function properly. This function does
39    /// not perform any I/O, it simply informs this object that some amount of
40    /// its buffer, returned from [`poll_fill_buf`], has been consumed and should
41    /// no longer be returned. As such, this function may do odd things if
42    /// [`poll_fill_buf`] isn't called before calling it.
43    ///
44    /// The `amt` must be `<=` the number of bytes in the buffer returned by
45    /// [`poll_fill_buf`].
46    ///
47    /// [`poll_read`]: AsyncRead::poll_read
48    /// [`poll_fill_buf`]: AsyncBufRead::poll_fill_buf
49    fn consume(self: Pin<&mut Self>, amt: usize);
50}
51
52impl AsyncBufRead for &[u8] {
53    fn poll_fill_buf(
54        self: Pin<&mut Self>,
55        _cx: &mut Context<'_>,
56    ) -> Poll<Result<&[u8], Self::Error>> {
57        Poll::Ready(Ok(*self))
58    }
59
60    fn consume(mut self: Pin<&mut Self>, amt: usize) {
61        *self = &self[amt..];
62    }
63}