refactor: consolidate escape functions and extract weight constants

- Create escape.rs with shared html_escape, html_escape_into, xml_escape
- Remove duplicate implementations from render.rs, highlight.rs, feed.rs, sitemap.rs
- Add DEFAULT_WEIGHT (50) and DEFAULT_WEIGHT_HIGH (99) constants to content.rs
- Replace all magic number weight defaults with named constants

No functional changes; all 67 tests pass.
This commit is contained in:
Timothy DeHerrera
2026-02-05 14:35:24 -07:00
parent 7a7dc929b1
commit 16f04eb95b
7 changed files with 84 additions and 55 deletions

63
src/escape.rs Normal file
View File

@@ -0,0 +1,63 @@
//! Text escaping utilities for HTML and XML output.
/// Escape HTML special characters for safe embedding in HTML content.
///
/// Escapes: `&`, `<`, `>`, `"`
pub fn html_escape(s: &str) -> String {
let mut result = String::with_capacity(s.len());
html_escape_into(&mut result, s);
result
}
/// Escape HTML characters into an existing string.
///
/// This is more efficient when building output incrementally.
pub fn html_escape_into(out: &mut String, s: &str) {
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
_ => out.push(c),
}
}
}
/// Escape XML special characters for safe embedding in XML documents.
///
/// Escapes: `&`, `<`, `>`, `"`, `'`
pub fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&apos;")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_html_escape() {
assert_eq!(html_escape("Hello & World"), "Hello &amp; World");
assert_eq!(html_escape("<tag>"), "&lt;tag&gt;");
assert_eq!(html_escape("\"quoted\""), "&quot;quoted&quot;");
}
#[test]
fn test_html_escape_into() {
let mut buf = String::new();
html_escape_into(&mut buf, "a < b");
assert_eq!(buf, "a &lt; b");
}
#[test]
fn test_xml_escape() {
assert_eq!(xml_escape("Hello & World"), "Hello &amp; World");
assert_eq!(xml_escape("<tag>"), "&lt;tag&gt;");
assert_eq!(xml_escape("\"quoted\""), "&quot;quoted&quot;");
assert_eq!(xml_escape("it's"), "it&apos;s");
}
}