#[derive(Default)]
pub struct Indenter {
indent: String,
prefix: String,
}
impl Indenter {
pub fn indent(mut self, n: usize) -> Self {
let mut indent = String::new();
for _ in 0..n {
indent.push(' ');
}
self.indent = indent;
self
}
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = prefix.into();
self
}
pub fn format(&self, text: impl AsRef<str>) -> String {
let mut output = String::new();
let text = text.as_ref();
for line in text.lines() {
output.push_str(&self.indent);
output.push_str(&self.prefix);
output.push_str(line);
output.push('\n');
}
output
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn no_indent_no_prefix() {
let i = Indenter::default();
assert_eq!(i.format("hello"), "hello\n");
}
#[test]
fn indent_no_prefix() {
let i = Indenter::default().indent(4);
assert_eq!(i.format("hello"), " hello\n");
}
#[test]
fn prefix_no_indent() {
let i = Indenter::default().prefix("> ");
assert_eq!(i.format("hello"), "> hello\n");
}
#[test]
fn prefix_and_indent() {
let i = Indenter::default().indent(4).prefix("> ");
assert_eq!(i.format("hello"), " > hello\n");
}
}