Merge pull request #427 from alexcrichton/no-recurse

Simplify the `reset_indentation` function
This commit is contained in:
Nick Fitzgerald 2018-07-09 11:00:02 -07:00 committed by GitHub
commit 3e0711ab0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -438,35 +438,23 @@ impl fmt::Display for MyError {
} }
fn reset_indentation(s: &str) -> String { fn reset_indentation(s: &str) -> String {
indent_recurse(s.lines(), 0) let mut indent: u32 = 0;
} let mut dst = String::new();
fn indent_recurse(mut lines: ::std::str::Lines, current_indent: usize) -> String { for line in s.lines() {
if let Some(line) = lines.next() { let line = line.trim();
let mut trimmed = line.trim().to_owned(); if line.starts_with('}') || line.ends_with('}') {
let mut next_indent = current_indent; indent = indent.saturating_sub(1);
let mut current_indent = current_indent;
if trimmed.ends_with('{') {
next_indent += 1;
} }
if trimmed.starts_with('}') || trimmed.ends_with('}') { let extra = if line.starts_with(':') || line.starts_with('?') { 1 } else { 0 };
if current_indent > 0 { for _ in 0..indent + extra {
current_indent -= 1; dst.push_str(" ");
}
if next_indent > 0 {
next_indent -= 1;
}
} }
if trimmed.starts_with('?') || trimmed.starts_with(':') { dst.push_str(line);
current_indent += 1; dst.push_str("\n");
if line.ends_with('{') {
indent += 1;
} }
format!(
"\n{}{}{}",
" ".repeat(current_indent),
&trimmed,
&indent_recurse(lines, next_indent)
)
} else {
String::new()
} }
return dst
} }