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
use std::fs::File;
use std::io::{self, Read};
use redirect::Redirect;
use tempfile::NamedTempFile;
pub struct BufferRedirect {
#[allow(dead_code)]
redir: Redirect<File>,
outer: File,
}
pub struct Buffer(File);
impl Read for Buffer {
#[inline(always)]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl BufferRedirect {
pub fn stdout() -> io::Result<BufferRedirect> {
let tempfile = NamedTempFile::new()?;
let inner = tempfile.reopen()?;
let outer = tempfile.reopen()?;
let redir = Redirect::stdout(inner)?;
Ok(BufferRedirect { redir, outer })
}
pub fn stderr() -> io::Result<BufferRedirect> {
let tempfile = NamedTempFile::new()?;
let inner = tempfile.reopen()?;
let outer = tempfile.reopen()?;
let redir = Redirect::stderr(inner)?;
Ok(BufferRedirect { redir, outer })
}
pub fn into_inner(self) -> Buffer {
Buffer(self.outer)
}
}
impl Read for BufferRedirect {
#[inline(always)]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.outer.read(buf)
}
}