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
use std::io::{self, Read, Write};
use BufferRedirect;
pub struct Hold {
buf_redir: Option<BufferRedirect>,
is_stdout: bool,
}
impl Hold {
pub fn stderr() -> io::Result<Hold> {
Ok(Hold {
buf_redir: Some(BufferRedirect::stderr()?),
is_stdout: false,
})
}
pub fn stdout() -> io::Result<Hold> {
Ok(Hold {
buf_redir: Some(BufferRedirect::stdout()?),
is_stdout: true,
})
}
}
impl Drop for Hold {
fn drop(&mut self) {
fn read_into<R: Read, W: Write>(mut from: R, mut to: W) {
let mut buf = [0u8; 4096];
loop {
match from.read(&mut buf) {
Ok(0) => break,
Ok(size) => {
if to.write_all(&buf[..size]).is_err() {
break;
}
}
Err(_) => break,
}
}
let _ = to.flush();
}
let from = self.buf_redir.take().unwrap().into_inner();
if self.is_stdout {
let stdout = io::stdout();
read_into(from, stdout.lock());
} else {
let stderr = io::stderr();
read_into(from, stderr.lock());
}
}
}