pub fn is_blank_or_comment_only(line: &str) -> bool {
if line.trim().is_empty() {
return true;
}
remove_comments(line).replace('>', "").trim().is_empty()
}
fn remove_comments(line: &str) -> String {
const OPEN: &str = "<!--";
const CLOSE: &str = "-->";
let mut remaining = line;
let mut kept = String::new();
loop {
let open = remaining.find(OPEN);
let close = remaining.find(CLOSE);
match (open, close) {
(None, None) => {
kept.push_str(remaining);
return kept;
}
(Some(open), None) => {
kept.push_str(&remaining[..open]);
return kept;
}
(None, Some(close)) => {
remaining = &remaining[close + CLOSE.len()..];
}
(Some(open), Some(close)) if close < open => {
remaining = &remaining[close + CLOSE.len()..];
}
(Some(open), Some(close)) => {
kept.push_str(&remaining[..open]);
remaining = &remaining[close + CLOSE.len()..];
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_line_is_blank() {
assert!(is_blank_or_comment_only(""));
assert!(is_blank_or_comment_only(" "));
assert!(is_blank_or_comment_only("\t"));
}
#[test]
fn a_comment_only_line_is_blank() {
assert!(is_blank_or_comment_only("<!-- c -->"));
assert!(is_blank_or_comment_only(" <!-- prettier-ignore --> "));
assert!(is_blank_or_comment_only("<!-- a --><!-- b -->"));
}
#[test]
fn an_unpaired_marker_is_blank_so_a_multi_line_comment_works_at_both_ends() {
assert!(is_blank_or_comment_only("<!--"));
assert!(is_blank_or_comment_only("-->"));
assert!(is_blank_or_comment_only("<!-- opens here"));
assert!(is_blank_or_comment_only("closes here -->"));
}
#[test]
fn the_convention_holds_inside_a_blockquote() {
assert!(is_blank_or_comment_only("> <!-- c -->"));
assert!(is_blank_or_comment_only(">> <!-- c -->"));
assert!(is_blank_or_comment_only(">"));
}
#[test]
fn a_line_carrying_anything_else_is_not_blank() {
assert!(!is_blank_or_comment_only("text"));
assert!(!is_blank_or_comment_only("text <!-- c -->"));
assert!(!is_blank_or_comment_only("<!-- c --> text"));
assert!(!is_blank_or_comment_only("<!-- a --> x <!-- b -->"));
assert!(!is_blank_or_comment_only("> text"));
assert!(!is_blank_or_comment_only("-->text<!--"));
}
}