1pub mod fmt;
2
3use std::ops::{Deref, DerefMut};
4
5pub struct PrettyPrinter<'a, 'b: 'a> {
6 padding: &'a str,
7 fmt: &'a mut std::fmt::Formatter<'b>,
8 on_newline: bool,
9}
10
11impl<'a, 'b> PrettyPrinter<'a, 'b> {
12 pub fn new(fmt: &'a mut std::fmt::Formatter<'b>, padding: &'a str) -> PrettyPrinter<'a, 'b> {
13 PrettyPrinter {
14 padding: padding,
15 fmt: fmt,
16 on_newline: false,
17 }
18 }
19
20 pub fn fmt(&'a mut self) -> &'a mut std::fmt::Formatter<'b> {
21 self.fmt
22 }
23}
24
25impl<'a, 'b> Deref for PrettyPrinter<'a, 'b> {
26 type Target = std::fmt::Formatter<'b>;
27
28 fn deref(&self) -> &Self::Target {
29 self.fmt
30 }
31}
32
33impl<'a, 'b> DerefMut for PrettyPrinter<'a, 'b> {
34 fn deref_mut(&mut self) -> &mut Self::Target {
35 self.fmt
36 }
37}
38
39impl<'a, 'b> std::fmt::Write for PrettyPrinter<'a, 'b> {
40 fn write_str(&mut self, mut s: &str) -> std::fmt::Result {
41 while !s.is_empty() {
42 if self.on_newline {
43 self.fmt.write_str(self.padding)?;
44 }
45
46 let split = match s.find('\n') {
47 Some(pos) => {
48 self.on_newline = true;
49 pos + 1
50 }
51 None => {
52 self.on_newline = false;
53 s.len()
54 }
55 };
56 self.fmt.write_str(&s[..split])?;
57 s = &s[split..];
58 }
59
60 Ok(())
61 }
62}
63
64
65pub struct ListDisplay<'a, T: std::fmt::Display + 'a>(pub &'a [T]);
66
67impl<'a, T: std::fmt::Display + 'a> std::fmt::Display for ListDisplay<'a, T> {
68 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
69 let mut i = self.0.iter().peekable();
70 while let Some(e) = i.next() {
71 e.fmt(f)?;
72 if i.peek().is_some() {
73 write!(f, ", ")?;
74 }
75 }
76 Ok(())
77 }
78}