1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use futures_core::future::Future;
use futures_core::task::{Waker, Poll};
use futures_io::{AsyncRead, AsyncWrite};
use std::boxed::Box;
use std::io;
use std::pin::Pin;
#[derive(Debug)]
pub struct CopyInto<'a, R: ?Sized, W: ?Sized> {
reader: &'a mut R,
read_done: bool,
writer: &'a mut W,
pos: usize,
cap: usize,
amt: u64,
buf: Box<[u8]>,
}
impl<R: ?Sized, W: ?Sized> Unpin for CopyInto<'_, R, W> {}
impl<'a, R: ?Sized, W: ?Sized> CopyInto<'a, R, W> {
pub(super) fn new(reader: &'a mut R, writer: &'a mut W) -> Self {
CopyInto {
reader,
read_done: false,
writer,
amt: 0,
pos: 0,
cap: 0,
buf: Box::new([0; 2048]),
}
}
}
impl<R, W> Future for CopyInto<'_, R, W>
where R: AsyncRead + ?Sized,
W: AsyncWrite + ?Sized,
{
type Output = io::Result<u64>;
fn poll(mut self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
let this = &mut *self;
loop {
if this.pos == this.cap && !this.read_done {
let n = try_ready!(this.reader.poll_read(waker, &mut this.buf));
if n == 0 {
this.read_done = true;
} else {
this.pos = 0;
this.cap = n;
}
}
while this.pos < this.cap {
let i = try_ready!(this.writer.poll_write(waker, &this.buf[this.pos..this.cap]));
if i == 0 {
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
} else {
this.pos += i;
this.amt += i as u64;
}
}
if this.pos == this.cap && this.read_done {
try_ready!(this.writer.poll_flush(waker));
return Poll::Ready(Ok(this.amt));
}
}
}
}