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:
63
src/escape.rs
Normal file
63
src/escape.rs
Normal 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("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape XML special characters for safe embedding in XML documents.
|
||||
///
|
||||
/// Escapes: `&`, `<`, `>`, `"`, `'`
|
||||
pub fn xml_escape(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_html_escape() {
|
||||
assert_eq!(html_escape("Hello & World"), "Hello & World");
|
||||
assert_eq!(html_escape("<tag>"), "<tag>");
|
||||
assert_eq!(html_escape("\"quoted\""), ""quoted"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_html_escape_into() {
|
||||
let mut buf = String::new();
|
||||
html_escape_into(&mut buf, "a < b");
|
||||
assert_eq!(buf, "a < b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xml_escape() {
|
||||
assert_eq!(xml_escape("Hello & World"), "Hello & World");
|
||||
assert_eq!(xml_escape("<tag>"), "<tag>");
|
||||
assert_eq!(xml_escape("\"quoted\""), ""quoted"");
|
||||
assert_eq!(xml_escape("it's"), "it's");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user