Add trim_tries

This commit is contained in:
Seiichi Uchida 2018-08-31 18:11:52 +09:00
parent 1b8f0ff1b6
commit 2880d59ec0

View file

@ -65,7 +65,7 @@
//! .qux
//! ```
use comment::rewrite_comment;
use comment::{rewrite_comment, CharClasses, FullCodeCharKind, RichChar};
use config::IndentStyle;
use expr::rewrite_call;
use lists::{extract_post_comment, extract_pre_comment, get_comment_end};
@ -870,3 +870,28 @@ fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool
_ => false,
}
}
/// Remove try operators (`?`s) that appear in the given string. If removing
/// them leaves an empty line, remove that line as well unless it is the first
/// line (we need the first newline for detecting pre/post comment).
fn trim_tries(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut line_buffer = String::with_capacity(s.len());
for (kind, rich_char) in CharClasses::new(s.chars()) {
match rich_char.get_char() {
'\n' => {
if result.is_empty() || !line_buffer.trim().is_empty() {
result.push_str(&line_buffer);
result.push('\n')
}
line_buffer.clear();
}
'?' if kind == FullCodeCharKind::Normal => continue,
c => line_buffer.push(c),
}
}
if !line_buffer.trim().is_empty() {
result.push_str(&line_buffer);
}
result
}