Skip to main content

moirai_async/io/
traits.rs

1use std::io::{self, IoSlice};
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5/// Read bytes asynchronously.
6pub trait AsyncRead {
7    /// Attempt to read from the source into the provided buffer.
8    fn poll_read(
9        self: Pin<&mut Self>,
10        cx: &mut Context<'_>,
11        buf: &mut [u8],
12    ) -> Poll<io::Result<usize>>;
13}
14
15/// Write bytes asynchronously.
16pub trait AsyncWrite {
17    /// Attempt to write bytes from the buffer to the destination.
18    fn poll_write(
19        self: Pin<&mut Self>,
20        cx: &mut Context<'_>,
21        buf: &[u8],
22    ) -> Poll<io::Result<usize>>;
23
24    /// Attempt to write bytes from several buffers in one operation.
25    ///
26    /// The default writes the first non-empty buffer through
27    /// [`poll_write`](Self::poll_write) and reports `Ok(0)` when every buffer
28    /// is empty. A writer with a scatter-gather primitive overrides this and
29    /// [`is_write_vectored`](Self::is_write_vectored) together.
30    fn poll_write_vectored(
31        self: Pin<&mut Self>,
32        cx: &mut Context<'_>,
33        bufs: &[IoSlice<'_>],
34    ) -> Poll<io::Result<usize>> {
35        let buf = bufs
36            .iter()
37            .find(|buf| !buf.is_empty())
38            .map_or(&[][..], |buf| &**buf);
39        self.poll_write(cx, buf)
40    }
41
42    /// Whether [`poll_write_vectored`](Self::poll_write_vectored) is cheaper
43    /// than one [`poll_write`](Self::poll_write) per buffer.
44    fn is_write_vectored(&self) -> bool {
45        false
46    }
47
48    /// Attempt to flush pending writes.
49    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
50
51    /// Attempt to close/shutdown the write side of the stream.
52    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
53}
54
55/// Read bytes from a buffered source asynchronously.
56pub trait AsyncBufRead: AsyncRead {
57    /// Returns the contents of the internal buffer, filling it with more data
58    /// from the inner reader if necessary.
59    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>>;
60
61    /// Consumes the specified amount of bytes from the internal buffer.
62    fn consume(self: Pin<&mut Self>, amt: usize);
63}