tokio_util::io

Function poll_write_buf

Source
pub fn poll_write_buf<T: AsyncWrite + ?Sized, B: Buf>(
    io: Pin<&mut T>,
    cx: &mut Context<'_>,
    buf: &mut B,
) -> Poll<Result<usize>>
Expand description

Try to write data from an implementer of the Buf trait to an AsyncWrite, advancing the buffer’s internal cursor.

This function will use vectored writes when the AsyncWrite supports vectored writes.

§Examples

File implements AsyncWrite and [Cursor<&[u8]>] implements Buf:

use tokio_util::io::poll_write_buf;
use tokio::io;
use tokio::fs::File;

use bytes::Buf;
use std::future::poll_fn;
use std::io::Cursor;
use std::pin::Pin;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut file = File::create("foo.txt").await?;
    let mut buf = Cursor::new(b"data to write");

    // Loop until the entire contents of the buffer are written to
    // the file.
    while buf.has_remaining() {
        poll_fn(|cx| poll_write_buf(Pin::new(&mut file), cx, &mut buf)).await?;
    }

    Ok(())
}