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
84
use std::io::{self, Read, Write};
use futures::{Future, Poll};
pub struct Copy<R, W> {
reader: R,
read_done: bool,
writer: W,
pos: usize,
cap: usize,
amt: u64,
buf: Box<[u8]>,
}
pub fn copy<R, W>(reader: R, writer: W) -> Copy<R, W>
where R: Read,
W: Write,
{
Copy {
reader: reader,
read_done: false,
writer: writer,
amt: 0,
pos: 0,
cap: 0,
buf: Box::new([0; 2048]),
}
}
impl<R, W> Future for Copy<R, W>
where R: Read,
W: Write,
{
type Item = u64;
type Error = io::Error;
fn poll(&mut self) -> Poll<u64, io::Error> {
loop {
if self.pos == self.cap && !self.read_done {
let n = try_nb!(self.reader.read(&mut self.buf));
if n == 0 {
self.read_done = true;
} else {
self.pos = 0;
self.cap = n;
}
}
while self.pos < self.cap {
let i = try_nb!(self.writer.write(&self.buf[self.pos..self.cap]));
self.pos += i;
self.amt += i as u64;
}
if self.pos == self.cap && self.read_done {
try_nb!(self.writer.flush());
return Ok(self.amt.into())
}
}
}
}