tokio/io/util/
write_all.rs1use crate::io::AsyncWrite;
2
3use pin_project_lite::pin_project;
4use std::future::Future;
5use std::io;
6use std::marker::PhantomPinned;
7use std::mem;
8use std::pin::Pin;
9use std::task::{ready, Context, Poll};
10
11pin_project! {
12 #[derive(Debug)]
13 #[must_use = "futures do nothing unless you `.await` or poll them"]
14 pub struct WriteAll<'a, W: ?Sized> {
15 writer: &'a mut W,
16 buf: &'a [u8],
17 #[pin]
19 _pin: PhantomPinned,
20 }
21}
22
23pub(crate) fn write_all<'a, W>(writer: &'a mut W, buf: &'a [u8]) -> WriteAll<'a, W>
24where
25 W: AsyncWrite + Unpin + ?Sized,
26{
27 WriteAll {
28 writer,
29 buf,
30 _pin: PhantomPinned,
31 }
32}
33
34impl<W> Future for WriteAll<'_, W>
35where
36 W: AsyncWrite + Unpin + ?Sized,
37{
38 type Output = io::Result<()>;
39
40 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
41 let me = self.project();
42 while !me.buf.is_empty() {
43 let n = loop {
44 match ready!(Pin::new(&mut *me.writer).poll_write(cx, me.buf)) {
45 Ok(n) => break n,
46 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
47 Err(e) => return Poll::Ready(Err(e)),
48 }
49 };
50 {
51 let (_, rest) = mem::take(&mut *me.buf).split_at(n);
52 *me.buf = rest;
53 }
54 if n == 0 {
55 return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
56 }
57 }
58
59 Poll::Ready(Ok(()))
60 }
61}