Skip to content

Commit

Permalink
wip for #207
Browse files Browse the repository at this point in the history
  • Loading branch information
jRimbault committed Sep 17, 2020
1 parent 276103d commit 559df5c
Showing 1 changed file with 41 additions and 20 deletions.
61 changes: 41 additions & 20 deletions src/indentation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,23 @@
/// ```
pub fn indent(s: &str, prefix: &str) -> String {
let mut result = String::new();
for line in s.lines() {
if line.chars().any(|c| !c.is_whitespace()) {
let mut lines = s.lines().peekable();

while let Some(line) = lines.next() {
if line.chars().next().is_none() {
result.push('\n');
continue;
}
let char_count = line.trim_start().chars().count();
if char_count != 0 {
result.push_str(prefix);
result.push_str(line);
}
result.push('\n');
if lines.peek().is_some() {
result.push('\n');
}
}

result
}

Expand Down Expand Up @@ -141,7 +151,7 @@ mod tests {
/// Add newlines. Ensures that the final line in the vector also
/// has a newline.
fn add_nl(lines: &[&str]) -> String {
lines.join("\n") + "\n"
lines.join("\n")
}

#[test]
Expand All @@ -152,27 +162,38 @@ mod tests {
#[test]
#[rustfmt::skip]
fn indent_nonempty() {
let x = vec![" foo",
"bar",
" baz"];
let y = vec!["// foo",
"//bar",
"// baz"];
assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y));
let text = r##" foo
bar
baz"##;

let expected = r##"// foo
//bar
// baz"##;
assert_eq!(indent(text, "//"), expected);
}

#[test]
#[rustfmt::skip]
fn indent_empty_line() {
let x = vec![" foo",
"bar",
"",
" baz"];
let y = vec!["// foo",
"//bar",
"",
"// baz"];
assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y));
let text = r##" foo
bar
baz"##;

let expected = r##"// foo
//bar
// baz"##;
assert_eq!(indent(text, "//"), expected);
}

#[test]
fn indented_text_should_have_the_same_number_of_lines_as_the_original_text() {
let texts = ["foo\nbar", "foo\nbar\n", "foo\nbar\nbaz"];
for original in texts.iter() {
let indented = indent(original, "");
assert_eq!(&indented, original);
}
}

#[test]
Expand Down

0 comments on commit 559df5c

Please sign in to comment.