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::fmt::{Debug, Formatter, Result, Write};
pub trait ExtendedDebug<'a> {
type Debug: 'a;
fn safe_debug(self) -> Self::Debug;
}
struct Escaper<W>(W);
impl<W> Write for Escaper<W>
where
W: Write,
{
fn write_str(&mut self, s: &str) -> Result {
for c in s.chars() {
self.write_char(c)?;
}
Ok(())
}
fn write_char(&mut self, c: char) -> Result {
match c {
'"' | '\\' => self.0.write_char('\\')?,
'\n' => return self.0.write_str("\\l"),
_ => {}
}
self.0.write_char(c)
}
}
pub struct CustomDebug<'a, T>(&'a T);
impl<'a, T> Debug for CustomDebug<'a, T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
writeln!(&mut Escaper(f), "{:#?}", &self.0)
}
}
impl<'a, T> ExtendedDebug<'a> for &'a T {
type Debug = CustomDebug<'a, T>;
fn safe_debug(self) -> Self::Debug {
CustomDebug(self)
}
}