use super::SerializeError;
use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event};
use quick_xml::Writer;
use std::io::Write;
pub(super) fn xml_error(error: impl std::fmt::Display) -> SerializeError {
SerializeError::XmlError(format!("HWPX XML: {error}"))
}
pub(super) fn xml_value<S: crate::storage::Storage>(
storage: &S,
value: impl std::fmt::Display,
) -> Result<String, SerializeError>
where
S::Error: std::fmt::Display,
{
storage.display(&value).map_err(xml_error)
}
pub fn write_xml_decl<W: Write>(w: &mut Writer<W>) -> Result<(), SerializeError> {
write_xml_decl_with_storage(w, &crate::storage::Unbounded)
}
pub(super) fn write_xml_decl_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
storage.bytes(0).map_err(xml_error)?;
let declaration = BytesDecl::from_start(BytesStart::from_content(
r#"xml version="1.0" encoding="UTF-8" standalone="yes""#,
3,
));
w.write_event(Event::Decl(declaration)).map_err(xml_error)
}
pub fn start_tag<W: Write>(w: &mut Writer<W>, name: &str) -> Result<(), SerializeError> {
w.write_event(Event::Start(BytesStart::new(name)))
.map_err(xml_error)
}
pub(super) fn start_tag_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
storage.bytes(0).map_err(xml_error)?;
start_tag(w, name)
}
pub fn end_tag<W: Write>(w: &mut Writer<W>, name: &str) -> Result<(), SerializeError> {
w.write_event(Event::End(BytesEnd::new(name)))
.map_err(xml_error)
}
pub(super) fn end_tag_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
storage.bytes(0).map_err(xml_error)?;
end_tag(w, name)
}
pub fn start_tag_attrs<W: Write>(
w: &mut Writer<W>,
name: &str,
attrs: &[(&str, &str)],
) -> Result<(), SerializeError> {
start_tag_attrs_with_storage(w, name, attrs, &crate::storage::Unbounded)
}
pub(super) fn start_tag_attrs_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
attrs: &[(&str, &str)],
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let bytes = storage
.binary(&XmlPayload::Tag(name, attrs))
.map_err(xml_error)?;
let content = std::str::from_utf8(&bytes).expect("XML encoder preserves UTF-8");
w.write_event(Event::Start(BytesStart::from_content(content, name.len())))
.map_err(xml_error)
}
pub fn empty_tag<W: Write>(
w: &mut Writer<W>,
name: &str,
attrs: &[(&str, &str)],
) -> Result<(), SerializeError> {
empty_tag_with_storage(w, name, attrs, &crate::storage::Unbounded)
}
pub(super) fn empty_tag_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
attrs: &[(&str, &str)],
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let bytes = storage
.binary(&XmlPayload::Tag(name, attrs))
.map_err(xml_error)?;
let content = std::str::from_utf8(&bytes).expect("XML encoder preserves UTF-8");
w.write_event(Event::Empty(BytesStart::from_content(content, name.len())))
.map_err(xml_error)
}
pub fn text<W: Write>(w: &mut Writer<W>, content: &str) -> Result<(), SerializeError> {
text_with_storage(w, content, &crate::storage::Unbounded)
}
pub(super) fn text_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
content: &str,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let bytes = storage
.binary(&XmlPayload::Text(content, Escape::Text))
.map_err(xml_error)?;
let content = std::str::from_utf8(&bytes).expect("XML encoder preserves UTF-8");
w.write_event(Event::Text(BytesText::from_escaped(content)))
.map_err(xml_error)
}
fn valid_xml_char(c: char) -> bool {
matches!(c,'\u{09}'|'\u{0A}'|'\u{0D}'|'\u{20}'..='\u{D7FF}'|'\u{E000}'..='\u{FFFD}'|'\u{10000}'..='\u{10FFFF}')
}
pub fn filter_xml_1_0_chars(s: &str) -> String {
s.chars().filter(|c| valid_xml_char(*c)).collect()
}
pub fn xml_escape(s: &str) -> String {
xml_escape_with_storage(s, &crate::storage::Unbounded).expect("unbounded XML escape")
}
pub(super) fn xml_escape_with_storage<S: crate::storage::Storage>(
s: &str,
storage: &S,
) -> Result<String, SerializeError>
where
S::Error: std::fmt::Display,
{
let bytes = storage
.binary(&XmlPayload::Text(s, Escape::Literal))
.map_err(xml_error)?;
Ok(String::from_utf8(bytes).expect("XML encoder preserves UTF-8"))
}
#[derive(Clone, Copy, PartialEq)]
enum Escape {
Literal,
Text,
Attribute,
}
enum XmlPayload<'a> {
Tag(&'a str, &'a [(&'a str, &'a str)]),
Text(&'a str, Escape),
}
impl crate::serializer::byte_writer::BinaryProducer for XmlPayload<'_> {
fn write<W: Write>(
&self,
w: &mut crate::serializer::byte_writer::ByteWriter<W>,
) -> std::io::Result<()> {
match self {
Self::Tag(name, attrs) => {
w.write_bytes(name.as_bytes())?;
for (key, value) in *attrs {
w.write_bytes(b" ")?;
w.write_bytes(key.as_bytes())?;
w.write_bytes(b"=\"")?;
write_escaped(w, value, Escape::Attribute)?;
w.write_bytes(b"\"")?;
}
}
Self::Text(value, mode) => write_escaped(w, value, *mode)?,
}
Ok(())
}
}
fn write_escaped<W: Write>(
w: &mut crate::serializer::byte_writer::ByteWriter<W>,
s: &str,
mode: Escape,
) -> std::io::Result<()> {
let mut start = 0;
for (at, c) in s.char_indices() {
let replacement = match c {
'\t' if mode == Escape::Attribute => Some("	"),
'\n' if mode == Escape::Attribute => Some(" "),
'\r' if mode != Escape::Literal => Some(" "),
'&' => Some("&"),
'<' => Some("<"),
'>' => Some(">"),
'"' => Some("""),
'\'' => Some("'"),
_ if !valid_xml_char(c) => Some(""),
_ => None,
};
if let Some(value) = replacement {
w.write_bytes(&s.as_bytes()[start..at])?;
w.write_bytes(value.as_bytes())?;
start = at + c.len_utf8();
}
}
w.write_bytes(&s.as_bytes()[start..])
}
pub(super) fn xml_replacen<S: crate::storage::Storage>(
input: impl AsRef<str>,
needle: &str,
replacement: &str,
limit: usize,
storage: &S,
) -> Result<String, SerializeError>
where
S::Error: std::fmt::Display,
{
struct Replacement<'a> {
input: &'a str,
needle: &'a str,
replacement: &'a str,
limit: usize,
}
impl std::fmt::Display for Replacement<'_> {
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut start = 0;
for (at, matched) in self.input.match_indices(self.needle).take(self.limit) {
out.write_str(&self.input[start..at])?;
out.write_str(self.replacement)?;
start = at + matched.len();
}
out.write_str(&self.input[start..])
}
}
xml_value(
storage,
Replacement {
input: input.as_ref(),
needle,
replacement,
limit,
},
)
}
pub(super) fn xml_insert<S: crate::storage::Storage>(
input: &mut String,
at: usize,
value: &str,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
storage
.reserve_string(input, value.len())
.map_err(xml_error)?;
input.insert_str(at, value);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xml_escape_drops_xml_invalid_control_chars() {
assert_eq!(xml_escape("a\u{03}b"), "ab");
for c in ['\u{00}', '\u{08}', '\u{0B}', '\u{0C}', '\u{0E}', '\u{1F}'] {
assert_eq!(
xml_escape(&format!("x{c}y")),
"xy",
"control {:#04x}",
c as u32
);
}
assert_eq!(xml_escape("a\u{FFFE}\u{FFFF}b"), "ab");
assert_eq!(xml_escape("a\tb\nc\rd"), "a\tb\nc\rd");
assert_eq!(xml_escape("<a & b>\"'"), "<a & b>"'");
assert_eq!(xml_escape("한글 A\u{1F600}"), "한글 A\u{1F600}");
}
#[test]
fn event_writers_drop_xml_invalid_chars_from_text_and_attributes() {
let mut bytes = Vec::new();
let mut writer = Writer::new(&mut bytes);
start_tag_attrs(&mut writer, "hp:test", &[("name", "a\u{03}b")]).unwrap();
text(&mut writer, "x\u{03}y & z").unwrap();
end_tag(&mut writer, "hp:test").unwrap();
empty_tag(&mut writer, "hp:empty", &[("value", "c\u{03}d")]).unwrap();
let xml = String::from_utf8(bytes).unwrap();
assert_eq!(
xml,
r#"<hp:test name="ab">xy & z</hp:test><hp:empty value="cd"/>"#
);
assert!(!xml.contains('\u{03}'));
}
#[test]
fn event_writers_escape_markup_chars_in_attribute_values() {
use quick_xml::{Reader, XmlVersion};
let mut bytes = Vec::new();
let mut writer = Writer::new(&mut bytes);
start_tag_attrs(&mut writer, "hp:start", &[("href", r#"a&b<c>d"e"#)]).unwrap();
end_tag(&mut writer, "hp:start").unwrap();
empty_tag(&mut writer, "hp:empty", &[("href", r#"x&y"z<w"#)]).unwrap();
let xml = String::from_utf8(bytes).unwrap();
assert!(
!xml.contains(r#"href="a&b<c>d"e""#),
"속성값이 이스케이프되지 않고 그대로 방출됨: {xml}"
);
assert!(
xml.contains("&") && xml.contains("<") && xml.contains(">"),
"{xml}"
);
assert!(!xml.contains("&amp;"), "이중 이스케이프됨: {xml}");
let mut reader = Reader::from_str(&xml);
let mut seen = Vec::new();
loop {
match reader.read_event().unwrap() {
Event::Start(e) | Event::Empty(e) => {
for a in e.attributes().flatten() {
seen.push(
a.normalized_value(XmlVersion::Implicit1_0)
.unwrap()
.into_owned(),
);
}
}
Event::Eof => break,
_ => {}
}
}
assert_eq!(seen, vec![r#"a&b<c>d"e"#, r#"x&y"z<w"#]);
}
}