pub fn dedent(text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let min_indent = lines
.iter()
.filter(|line| !line.trim().is_empty())
.map(|line| {
let mut spaces = 0;
for c in line.chars() {
if c == ' ' {
spaces += 1;
} else if c == '\t' {
spaces += 4; } else {
break;
}
}
spaces
})
.min()
.unwrap_or(0);
lines
.iter()
.map(|line| {
if line.trim().is_empty() {
return String::new();
}
let mut count = 0;
let mut chars = line.chars().peekable();
while count < min_indent && chars.peek().is_some() {
match chars.peek() {
Some(' ') => {
chars.next();
count += 1;
}
Some('\t') => {
chars.next();
count += 4;
}
_ => break,
}
}
chars.collect::<String>()
})
.collect::<Vec<String>>()
.join("\n")
}
pub fn prefix(text: &str, prefix: &str) -> String {
text.lines()
.map(|line| format!("{}{}", prefix, line))
.collect::<Vec<String>>()
.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dedent() {
let indented = " line 1\n line 2\n line 3";
let dedented = dedent(indented);
assert_eq!(dedented, "line 1\nline 2\n line 3");
}
#[test]
fn test_prefix() {
let text = "line 1\nline 2\nline 3";
let prefixed = prefix(text, " ");
assert_eq!(prefixed, " line 1\n line 2\n line 3");
}
}