futures_util/io/
write_all.rs

1use futures_core::future::Future;
2use futures_core::ready;
3use futures_core::task::{Context, Poll};
4use futures_io::AsyncWrite;
5use std::io;
6use std::mem;
7use std::pin::Pin;
8
9/// Future for the [`write_all`](super::AsyncWriteExt::write_all) method.
10#[derive(Debug)]
11#[must_use = "futures do nothing unless you `.await` or poll them"]
12pub struct WriteAll<'a, W: ?Sized> {
13    writer: &'a mut W,
14    buf: &'a [u8],
15}
16
17impl<W: ?Sized + Unpin> Unpin for WriteAll<'_, W> {}
18
19impl<'a, W: AsyncWrite + ?Sized + Unpin> WriteAll<'a, W> {
20    pub(super) fn new(writer: &'a mut W, buf: &'a [u8]) -> Self {
21        Self { writer, buf }
22    }
23}
24
25impl<W: AsyncWrite + ?Sized + Unpin> Future for WriteAll<'_, W> {
26    type Output = io::Result<()>;
27
28    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
29        let this = &mut *self;
30        while !this.buf.is_empty() {
31            let n = ready!(Pin::new(&mut this.writer).poll_write(cx, this.buf))?;
32            {
33                let (_, rest) = mem::take(&mut this.buf).split_at(n);
34                this.buf = rest;
35            }
36            if n == 0 {
37                return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
38            }
39        }
40
41        Poll::Ready(Ok(()))
42    }
43}