>().join(" ")
}
/// Collapses runs of whitespace within lines, trims lines and keeps at most
/// one blank line between paragraphs.
pub(crate) fn normalize_whitespace(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut pending_blank = false;
for line in s.split('\n') {
let line = collapse_inline_whitespace(line);
if line.is_empty() {
pending_blank = !out.is_empty();
continue;
}
if !out.is_empty() {
out.push('\n');
if pending_blank {
out.push('\n');
}
}
pending_blank = false;
out.push_str(&line);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn extracts_text_and_title() {
let html = r#"
Hello & welcome
Heading
First paragraph with bold and a link.
tpl
a
b
Entities: <tag> "q" 's' AB end &unknown; & alone
"#;
let extracted = html_to_text(html);
assert_eq!(extracted.title.as_deref(), Some("Hello & welcome"));
assert_eq!(
extracted.text,
"Heading\n\nFirst paragraph with bold and a link.\n\n- one\n- two\n\na\nb\n\nEntities: \"q\" 's' AB end &unknown; & alone"
);
}
#[test]
fn head_without_close_ends_at_body() {
let extracted = html_to_text("junkvisible");
assert_eq!(extracted.text, "visible");
assert_eq!(extracted.title, None);
}
#[test]
fn unclosed_script_drops_rest() {
assert_eq!(html_to_text("a
z").text, "xz");
}
#[test]
fn pre_keeps_newlines() {
assert_eq!(html_to_text("a\nb
").text, "a\nb");
}
#[test]
fn literal_less_than_and_numeric_entities() {
assert_eq!(
decode_entities("1 < 2 😀"),
"1 < 2 \u{fffd} \u{fffd} 😀"
);
assert_eq!(html_to_text("a < b").text, "a < b");
}
}