Skip to main content

write_all_vectored

Function write_all_vectored 

Source
pub fn write_all_vectored<'a, 'b, W>(
    writer: &'a mut W,
    bufs: &'a mut [IoSlice<'b>],
) -> WriteAllVectored<'a, 'b, W> 
where W: AsyncWrite + Unpin + ?Sized,
Available on crate feature io only.
Expand description

Like write_all but writes all data from multiple buffers into this writer.

This function writes multiple (possibly non-contiguous) buffers into the writer, using the writev syscall to potentially write in a single system call.

Equivalent to:

async fn write_all_vectored<W: AsyncWrite + Unpin + ?Sized>(
    writer: &mut W,
    mut bufs: &mut [IoSlice<'_>]
) -> io::Result<()> {
    while !bufs.is_empty() {
        let n = write_vectored(writer, bufs).await?;
        if n == 0 {
            return Err(io::ErrorKind::WriteZero.into());
        }
        IoSlice::advance_slices(&mut bufs, n);
    }
    Ok(())
}

§Cancel safety

This method is not cancellation safe. If it is used as the event in a tokio::select! statement and some other branch completes first, then the provided buffer may have been partially written, but future calls to write_all_vectored will have lost its place in the buffer.

§Examples

use tokio_util::io::write_all_vectored;
use std::io::IoSlice;

#[tokio::main(flavor = "current_thread")]
async fn main() -> std::io::Result<()> {

    let mut writer = Vec::new();
    let bufs = &mut [
        IoSlice::new(&[1]),
        IoSlice::new(&[2, 3]),
        IoSlice::new(&[4, 5, 6]),
    ];

    write_all_vectored(&mut writer, bufs).await?;

    // Note: `bufs` has been modified by `IoSlice::advance_slices` and should not be reused.
    assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
    Ok(())
}

§Notes

See the documentation for Write::write_all_vectored from std. After calling this function, the buffer slices may have been advanced and should not be reused.