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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use std::io::{self, Write, Cursor};
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
thread_local! {
pub static THR_OUT: RefCell<Arc<Mutex<WriteIO>>> = RefCell::new(Arc::new(Mutex::new(WriteIO::StdOut)));
pub static THR_ERR: RefCell<Arc<Mutex<WriteIO>>> = RefCell::new(Arc::new(Mutex::new(WriteIO::StdErr)));
}
#[macro_export]
macro_rules! tprintln {
() => {
{
($crate::thrio::THR_OUT).with(|tout| {
writeln!(*tout.borrow_mut().lock().unwrap()).unwrap();
});
}
};
($($arg:tt)*) => {
{
($crate::thrio::THR_OUT).with(|tout| {
writeln!(*tout.borrow_mut().lock().unwrap(), $($arg)*).unwrap();
});
}
};
}
#[macro_export]
macro_rules! teprintln {
() => {
{
($crate::thrio::THR_OUT).with(|tout| {
writeln!(*terr.borrow_mut().lock().unwrap()).unwrap();
});
}
};
($($arg:tt)*) => {
{
($crate::thrio::THR_OUT).with(|tout| {
writeln!(*terr.borrow_mut().lock().unwrap(), $($arg)*).unwrap();
});
}
};
}
pub fn set_out(out: &Arc<Mutex<WriteIO>>) {
THR_OUT.with(|tout| {
*tout.borrow_mut() = Arc::clone(out);
});
}
pub fn set_err(err: &Arc<Mutex<WriteIO>>) {
THR_ERR.with(|terr| {
*terr.borrow_mut() = Arc::clone(err);
});
}
pub fn reset_out() {
THR_OUT.with(|tout| {
*tout.borrow_mut() = Arc::new(Mutex::new(WriteIO::StdOut));
});
}
pub fn reset_err() {
THR_OUT.with(|tout| {
*tout.borrow_mut() = Arc::new(Mutex::new(WriteIO::StdErr));
});
}
pub enum WriteIO {
StdOut,
StdErr,
Cursor(Cursor<Vec<u8>>),
}
impl WriteIO {
pub fn new() -> WriteIO {
WriteIO::Cursor(Cursor::new(Vec::new()))
}
}
impl Write for WriteIO {
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
match self {
WriteIO::StdOut => io::stdout().lock().write(buf),
WriteIO::StdErr => io::stderr().lock().write(buf),
WriteIO::Cursor(c) => c.write(buf),
}
}
fn flush(&mut self) -> Result<(), io::Error> {
match self {
WriteIO::StdOut => io::stdout().lock().flush(),
WriteIO::StdErr => io::stderr().lock().flush(),
WriteIO::Cursor(c) => c.flush(),
}
}
}