use serde::Serialize;
use crate::ParseError;
const XML_DECLARATION: &str = r#"<?xml version="1.0" encoding="UTF-8"?>"#;
pub fn to_string<T: Serialize>(value: &T) -> Result<String, ParseError> {
quick_xml::se::to_string(value).map_err(ParseError::Serialize)
}
pub fn to_string_with_declaration<T: Serialize>(value: &T) -> Result<String, ParseError> {
let body = quick_xml::se::to_string(value).map_err(ParseError::Serialize)?;
Ok(format!("{XML_DECLARATION}{body}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_string_with_declaration_prepends_declaration() {
#[derive(serde::Serialize)]
struct Msg {
value: u32,
}
let result = to_string_with_declaration(&Msg { value: 42 }).unwrap();
assert!(
result.starts_with(r#"<?xml version="1.0" encoding="UTF-8"?>"#),
"expected XML declaration at start, got: {result}"
);
assert!(
result.contains("<value>42</value>"),
"expected body in output"
);
}
#[test]
fn to_string_no_declaration() {
#[derive(serde::Serialize)]
struct Msg {
value: u32,
}
let result = to_string(&Msg { value: 7 }).unwrap();
assert!(
!result.starts_with("<?xml"),
"to_string must not include XML declaration"
);
assert!(result.contains("<value>7</value>"));
}
}