pad_adapter/
lib.rs

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
#![no_std]

use core::fmt::{self, Formatter, Write};

/// Pad adapter inserts the padding after each newline except the last.
///
/// The default padding is `    `.
pub struct PadAdapter<'a, 'b: 'a, 'c> {
    fmt: &'a mut Formatter<'b>,
    padding: &'c str,
    state: State,
}

impl<'a, 'b: 'a, 'c> PadAdapter<'a, 'b, 'c> {
    /// Creates a new pad adapter with default padding.
    pub fn new(fmt: &'a mut Formatter<'b>) -> Self {
        Self {
            fmt,
            padding: "    ",
            state: Default::default(),
        }
    }

    /// Creates a new pad adapter with the padding.
    pub fn with_padding(fmt: &'a mut Formatter<'b>, padding: &'c str) -> Self {
        Self {
            fmt,
            padding,
            state: Default::default(),
        }
    }
}

impl Write for PadAdapter<'_, '_, '_> {
    fn write_str(&mut self, mut s: &str) -> fmt::Result {
        while !s.is_empty() {
            if self.state.on_newline {
                self.fmt.write_str(self.padding)?;
            }
            let split = match s.find('\n') {
                Some(pos) => {
                    self.state.on_newline = true;
                    pos + 1
                }
                None => {
                    self.state.on_newline = false;
                    s.len()
                }
            };
            self.fmt.write_str(&s[..split])?;
            s = &s[split..];
        }
        Ok(())
    }
}

struct State {
    on_newline: bool,
}

impl Default for State {
    fn default() -> Self {
        Self { on_newline: true }
    }
}