tokio/io/util/
write_buf.rs

1use crate::io::AsyncWrite;
2
3use bytes::Buf;
4use pin_project_lite::pin_project;
5use std::future::Future;
6use std::io::{self, IoSlice};
7use std::marker::PhantomPinned;
8use std::pin::Pin;
9use std::task::{ready, Context, Poll};
10
11pin_project! {
12    /// A future to write some of the buffer to an `AsyncWrite`.
13    #[derive(Debug)]
14    #[must_use = "futures do nothing unless you `.await` or poll them"]
15    pub struct WriteBuf<'a, W, B> {
16        writer: &'a mut W,
17        buf: &'a mut B,
18        #[pin]
19        _pin: PhantomPinned,
20    }
21}
22
23/// Tries to write some bytes from the given `buf` to the writer in an
24/// asynchronous manner, returning a future.
25pub(crate) fn write_buf<'a, W, B>(writer: &'a mut W, buf: &'a mut B) -> WriteBuf<'a, W, B>
26where
27    W: AsyncWrite + Unpin,
28    B: Buf,
29{
30    WriteBuf {
31        writer,
32        buf,
33        _pin: PhantomPinned,
34    }
35}
36
37impl<W, B> Future for WriteBuf<'_, W, B>
38where
39    W: AsyncWrite + Unpin,
40    B: Buf,
41{
42    type Output = io::Result<usize>;
43
44    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
45        const MAX_VECTOR_ELEMENTS: usize = 64;
46
47        let me = self.project();
48
49        if !me.buf.has_remaining() {
50            return Poll::Ready(Ok(0));
51        }
52
53        let n = if me.writer.is_write_vectored() {
54            let mut slices = [IoSlice::new(&[]); MAX_VECTOR_ELEMENTS];
55            let cnt = me.buf.chunks_vectored(&mut slices);
56            ready!(Pin::new(&mut *me.writer).poll_write_vectored(cx, &slices[..cnt]))?
57        } else {
58            ready!(Pin::new(&mut *me.writer).poll_write(cx, me.buf.chunk()))?
59        };
60
61        me.buf.advance(n);
62        Poll::Ready(Ok(n))
63    }
64}