The headless browser for AI agents and web scraping
perf(dom): copy unescaped runs whole when serializing
404Humanefb57d838a5c
diff --git a/crates/obscura-dom/src/serialize.rs b/crates/obscura-dom/src/serialize.rsindex 8d54d9d5..63164e69 100644--- a/crates/obscura-dom/src/serialize.rs+++ b/crates/obscura-dom/src/serialize.rs@@ -176,32 +176,41 @@ impl DomTree {}}-// "Escaping a string" from the HTML Standard. Attribute mode escapes `<` and-// `>` too: left literal, a value such as `</noscript><img>` ends its raw-text-// parent when the markup is parsed again.+// "Escaping a string" from the HTML Standard. Attribute mode escapes `"`, and+// `<` and `>` too: left literal, a value such as `</noscript><img>` ends its+// raw-text parent when the markup is parsed again.fn escape_text(s: &str, buf: &mut String) {- for c in s.chars() {- match c {- '&' => buf.push_str("&"),- '\u{a0}' => buf.push_str(" "),- '<' => buf.push_str("<"),- '>' => buf.push_str(">"),- _ => buf.push(c),- }- }+ escape(s, false, buf);}fn escape_attr(s: &str, buf: &mut String) {- for c in s.chars() {- match c {- '&' => buf.push_str("&"),- '\u{a0}' => buf.push_str(" "),- '"' => buf.push_str("""),- '<' => buf.push_str("<"),- '>' => buf.push_str(">"),- _ => buf.push(c),- }+ escape(s, true, buf);+}++/// Copies the runs between escaped characters whole; most text has none.+fn escape(s: &str, attribute: bool, buf: &mut String) {+ let bytes = s.as_bytes();+ let mut copied = 0;+ let mut i = 0;+ while i < bytes.len() {+ let (entity, len) = match bytes[i] {+ b'&' => ("&", 1),+ b'<' => ("<", 1),+ b'>' => (">", 1),+ b'"' if attribute => (""", 1),+ // U+00A0 NO-BREAK SPACE in UTF-8.+ 0xC2 if bytes.get(i + 1) == Some(&0xA0) => (" ", 2),+ _ => {+ i += 1;+ continue;+ }+ };+ buf.push_str(&s[copied..i]);+ buf.push_str(entity);+ i += len;+ copied = i;}+ buf.push_str(&s[copied..]);}fn is_void_element(tag: &str) -> bool {@@ -346,6 +355,19 @@ mod tests {assert!(parse_html(&out).query_selector("img").unwrap().is_none(), "{out}");}+ #[test]+ fn escaping_keeps_every_other_character_including_multibyte_ones() {+ let mut out = String::new();+ super::escape_text("\u{a0}é&\u{a1}<ع>\u{c2}\u{1f600}\"\u{a0}", &mut out);+ assert_eq!(out, " é&\u{a1}<ع>\u{c2}\u{1f600}\" ");+ out.clear();+ super::escape_attr("\"a\u{a0}<b>&\"", &mut out);+ assert_eq!(out, ""a <b>&"");+ out.clear();+ super::escape_text("", &mut out);+ assert_eq!(out, "");+ }+#[test]fn test_void_elements() {let tree = parse_html(r#"<img src="test.png"><br>"#);