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
use std::io::{Read, Result, Write};
pub struct TeeReader<R, W> {
read: R,
output: W,
force_flush: bool,
}
impl<R, W> TeeReader<R, W> {
pub fn new(read: R, output: W, force_flush: bool) -> Self {
Self {
read,
output,
force_flush,
}
}
}
impl<R: Read, W: Write> Read for TeeReader<R, W> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let n = self.read.read(buf)?;
self.output.write_all(&buf[..n])?;
if self.force_flush {
self.output.flush()?;
}
Ok(n)
}
}
impl<R: Read + Clone, W: Write + Clone> Clone for TeeReader<R, W> {
fn clone(&self) -> Self {
Self {
read: self.read.clone(),
output: self.output.clone(),
force_flush: self.force_flush,
}
}
}
pub struct TeeWriter<L, R> {
write: L,
output: R,
}
impl<L, R> TeeWriter<L, R> {
pub fn new(write: L, output: R) -> Self {
Self { write, output }
}
}
impl<L: Write, R: Write> Write for TeeWriter<L, R> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let n = self.write.write(buf)?;
let _ = self.output.write(&buf[..n])?;
Ok(n)
}
fn flush(&mut self) -> Result<()> {
self.write.flush()
}
}