use quick_xml::se::{SeError, Serializer};
use serde::Serialize;
const INDENT_WIDTH: usize = 2;
pub fn to_string<T: Serialize>(value: &T) -> Result<String, SeError> {
let mut output = String::new();
let mut serializer = Serializer::new(&mut output);
serializer.indent(' ', INDENT_WIDTH);
value.serialize(serializer)?;
output.push('\n');
Ok(output)
}
pub(crate) fn is_compact_nested(value: &str) -> bool {
let value = value.trim();
!value.contains('\n') && value.contains("><") && !value.ends_with("/>")
}
#[cfg(test)]
mod tests {
use serde::Serialize;
use super::*;
#[derive(Serialize)]
struct Document {
child: Child,
}
#[derive(Serialize)]
struct Child {
value: String,
}
#[test]
fn serializes_nested_documents_with_two_spaces_and_a_newline() {
let output = to_string(&Document {
child: Child {
value: "ready".to_string(),
},
})
.unwrap();
assert_eq!(
output,
"<Document>\n <child>\n <value>ready</value>\n </child>\n</Document>\n"
);
}
#[test]
fn detects_only_compact_nested_documents() {
assert!(is_compact_nested("<root><child>value</child></root>"));
assert!(!is_compact_nested(
"<root>\n <child>value</child>\n</root>\n"
));
assert!(!is_compact_nested("<root/>\n"));
}
}