1pub struct Formatter<'a> {
9 buf: &'a mut String,
10}
11
12impl<'a> Formatter<'a> {
13 #[inline]
15 pub fn new(buf: &'a mut String) -> Self {
16 Self { buf }
17 }
18
19 #[inline]
21 pub fn write_str(&mut self, s: &str) {
22 self.buf.push_str(s);
23 }
24
25 #[inline]
27 pub fn write_char(&mut self, c: char) {
28 self.buf.push(c);
29 }
30}
31
32impl std::fmt::Write for Formatter<'_> {
33 fn write_str(&mut self, s: &str) -> std::fmt::Result {
34 Formatter::write_str(self, s);
35 Ok(())
36 }
37
38 fn write_char(&mut self, c: char) -> std::fmt::Result {
39 Formatter::write_char(self, c);
40 Ok(())
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 #[test]
49 fn write_str_is_verbatim() {
50 let mut buf = String::new();
51 let mut f = Formatter::new(&mut buf);
52 f.write_str("<b>&\"'</b>");
53 assert_eq!(buf, "<b>&\"'</b>");
54 }
55
56 #[test]
57 fn write_char_is_verbatim() {
58 let mut buf = String::new();
59 let mut f = Formatter::new(&mut buf);
60 f.write_char('<');
61 f.write_char('é');
62 assert_eq!(buf, "<é");
63 }
64
65 #[test]
66 fn fmt_write_is_verbatim() {
67 use std::fmt::Write;
68
69 let (one, two) = (1, "two");
70 let mut buf = String::new();
71 let mut f = Formatter::new(&mut buf);
72 write!(f, "{one} < {two}").unwrap();
73 assert_eq!(buf, "1 < two");
74 }
75}