1 | use std::pin::Pin; |
2 | use std::future::Future; |
3 | |
4 | use crate::io::{self, Write}; |
5 | use crate::task::{Context, Poll}; |
6 | |
7 | #[doc (hidden)] |
8 | #[allow (missing_debug_implementations)] |
9 | #[must_use ] |
10 | pub struct WriteFmtFuture<'a, T: Unpin + ?Sized> { |
11 | pub(crate) writer: &'a mut T, |
12 | pub(crate) res: Option<io::Result<Vec<u8>>>, |
13 | pub(crate) buffer: Option<Vec<u8>>, |
14 | pub(crate) amt: usize, |
15 | } |
16 | |
17 | impl<T: Write + Unpin + ?Sized> Future for WriteFmtFuture<'_, T> { |
18 | type Output = io::Result<()>; |
19 | |
20 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
21 | // Process the internal Result the first time we run. |
22 | if self.buffer.is_none() { |
23 | match self.res.take().unwrap() { |
24 | Err(err) => return Poll::Ready(Err(err)), |
25 | Ok(buffer) => self.buffer = Some(buffer), |
26 | }; |
27 | } |
28 | |
29 | // Get the types from the future. |
30 | let Self { |
31 | writer, |
32 | amt, |
33 | buffer, |
34 | .. |
35 | } = &mut *self; |
36 | let buffer = buffer.as_mut().unwrap(); |
37 | |
38 | // Copy the data from the buffer into the writer until it's done. |
39 | loop { |
40 | if *amt == buffer.len() { |
41 | futures_core::ready!(Pin::new(&mut **writer).poll_flush(cx))?; |
42 | return Poll::Ready(Ok(())); |
43 | } |
44 | let i = futures_core::ready!(Pin::new(&mut **writer).poll_write(cx, &buffer[*amt..]))?; |
45 | if i == 0 { |
46 | return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); |
47 | } |
48 | *amt += i; |
49 | } |
50 | } |
51 | } |
52 | |