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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use std::fmt;

pub struct Indented<'a, D: ?Sized> {
    inner: &'a mut D,
    level: usize,
    indent_required: bool,
}

/// Helper function for creating a default indenter
pub fn indented<D: ?Sized>(f: &mut D, level: usize) -> Indented<'_, D> {
    Indented {
        inner: f,
        level,
        indent_required: true,
    }
}

impl<T> fmt::Write for Indented<'_, T>
where
    T: fmt::Write + ?Sized,
{
    fn write_str(&mut self, s: &str) -> fmt::Result {
        for (ind, line) in s.split('\n').enumerate() {
            if ind > 0 {
                self.inner.write_char('\n')?;
                self.indent_required = true;
            }

            if self.indent_required && !line.is_empty() {
                write!(self.inner, "{:indent$}{}", "", line, indent = self.level)?;
                self.indent_required = false;
            } else if !line.is_empty() {
                write!(self.inner, "{}", line)?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::fmt::Write;

    #[test]
    fn test_simple() {
        let output = &mut String::new();
        let input = "Hello!";
        let expected = "    Hello!";

        write!(indented(output, 4), "{}", input).unwrap();

        assert_eq!(output, expected);
    }

    #[test]
    fn test_multi_line() {
        let output = &mut String::new();
        let input = "Hello!\nThere!";
        let expected = "    Hello!\n    There!";

        write!(indented(output, 4), "{}", input).unwrap();

        assert_eq!(output, expected);
    }

    #[test]
    fn test_multi_write() {
        let output = &mut String::new();
        let input = "Hello!\nThere!";
        let expected = "    Hello!\n    There!\n    Hello!\n    There!\n";

        writeln!(indented(output, 4), "{}", input).unwrap();
        writeln!(indented(output, 4), "{}", input).unwrap();

        assert_eq!(output, expected);
    }

    #[test]
    fn test_nested_indents() {
        let output = &mut String::new();
        let input = "Hello!\nThere!";

        let mut level1 = indented(output, 2);
        writeln!(level1, "{}", input).unwrap();

        let mut level2 = indented(&mut level1, 2);
        writeln!(level2, "{}", input).unwrap();

        assert_eq!(output, "  Hello!\n  There!\n    Hello!\n    There!\n")
    }
}