From aa915867700861813ad81a25a39e3e43d0f56074 Mon Sep 17 00:00:00 2001 From: Jayson Reis Date: Thu, 1 Sep 2022 17:44:22 +0200 Subject: [PATCH] feat: Allow srializer with custom eventwriter This way, one can configure parametes for the xml crate, like indentation --- src/ser/mod.rs | 4 ++++ tests/emiter_config.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tests/emiter_config.rs diff --git a/src/ser/mod.rs b/src/ser/mod.rs index 8130a8d..4d12163 100644 --- a/src/ser/mod.rs +++ b/src/ser/mod.rs @@ -100,6 +100,10 @@ where Self::new_from_writer(EmitterConfig::new().create_writer(writer)) } + pub fn with_writer(writer: EventWriter) -> Self { + Self::new_from_writer(writer) + } + fn next(&mut self, event: XmlEvent) -> Result<()> { self.writer.write(event)?; Ok(()) diff --git a/tests/emiter_config.rs b/tests/emiter_config.rs new file mode 100644 index 0000000..5f565b0 --- /dev/null +++ b/tests/emiter_config.rs @@ -0,0 +1,26 @@ +use serde::Serialize; +use serde_xml_rs::Serializer; +use xml::EmitterConfig; + +#[derive(Debug, Serialize, PartialEq)] +struct Item { + name: String, + source: String, +} + +#[test] +fn serializer_should_accept_custom_emitter() { + let item = Item { + name: "john".to_string(), + source: "outerworld".to_string(), + }; + let mut output = Vec::new(); + { + let w = EmitterConfig::default() + .perform_indent(true) + .create_writer(&mut output); + let mut serializer = Serializer::with_writer(w); + item.serialize(&mut serializer).unwrap(); + } + assert_eq!("\n\n john\n outerworld\n", String::from_utf8_lossy(&output)); +}