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
use {
lazy_static::lazy_static,
std::{
io::{self, Write},
sync::Mutex,
},
};
pub struct LogEndpoint(Vec<u8>);
lazy_static! {
pub static ref LOG_WRITER: Mutex<Box<dyn Write + Send>> = Mutex::new(Box::new(io::stdout()));
}
impl LogEndpoint {
pub fn new(name: &[u8]) -> LogEndpoint {
LogEndpoint(name.to_owned())
}
pub fn write_entry(&self, mut msg: &[u8]) -> io::Result<()> {
const LOG_ENDPOINT_DELIM: &[u8] = b" :: ";
if msg.last() == Some(&b'\n') {
msg = &msg[..msg.len() - 1];
}
if msg.is_empty() {
return Ok(());
}
let mut to_write =
Vec::with_capacity(msg.len() + self.0.len() + LOG_ENDPOINT_DELIM.len() + 1);
to_write.extend_from_slice(&self.0);
to_write.extend_from_slice(LOG_ENDPOINT_DELIM);
for &byte in msg {
if byte == b'\n' {
to_write.extend_from_slice(br"\n");
} else {
to_write.push(byte);
}
}
to_write.push(b'\n');
LOG_WRITER.lock().unwrap().write_all(&to_write)
}
}
impl Write for LogEndpoint {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.write_entry(buf)?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
LOG_WRITER.lock().unwrap().flush()
}
}