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
85
use std::fmt;
use std::io;
use std::result;
use std::sync::Mutex;
#[derive(Clone)]
pub enum WriterImpl {
Stdout,
Stderr,
Info,
Noop,
}
fn write_to_io_writer(writer: &mut io::Write, s: &str) -> result::Result<(), fmt::Error> {
use std::fmt::Write;
let mut buf = String::new();
buf.write_str(s)?;
writer.write_all(&buf.into_bytes()[..]).unwrap();
Ok(())
}
lazy_static! {
static ref WRITER_IMPL: Mutex<WriterImpl> = Mutex::new(WriterImpl::Info);
}
pub fn set_writer_impl(i: WriterImpl) {
let mut guard = match WRITER_IMPL.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
*guard = i;
}
pub struct Writer {
writer_impl: WriterImpl,
}
impl fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> result::Result<(), fmt::Error> {
match self.writer_impl {
WriterImpl::Stdout => write_to_io_writer(&mut io::stdout(), s),
WriterImpl::Stderr => write_to_io_writer(&mut io::stderr(), s),
WriterImpl::Info => {
info!("{}", s);
Ok(())
},
WriterImpl::Noop => Ok(()),
}
}
}
pub fn get_writer_impl() -> Writer {
let guard = match WRITER_IMPL.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
Writer { writer_impl: (*guard).clone() }
}