Skip to main content

topcoat_view/
format.rs

1/// A plain string writer that render output accumulates into.
2///
3/// `Formatter` is escaping-agnostic: [`write_str`](Self::write_str) and
4/// [`write_char`](Self::write_char) append exactly what they are given. Text
5/// that needs to be made safe for an HTML position is written through an
6/// [`HtmlWriter`](crate::HtmlWriter) created for the matching
7/// [`HtmlContext`](crate::HtmlContext) instead.
8pub struct Formatter<'a> {
9    buf: &'a mut String,
10}
11
12impl<'a> Formatter<'a> {
13    /// Creates a new `Formatter` that writes into the given destination.
14    #[inline]
15    pub fn new(buf: &'a mut String) -> Self {
16        Self { buf }
17    }
18
19    /// Writes a string verbatim.
20    #[inline]
21    pub fn write_str(&mut self, s: &str) {
22        self.buf.push_str(s);
23    }
24
25    /// Writes a single character verbatim.
26    #[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}