Skip to main content

redispatch_xml/
serialize.rs

1//! Serialization helpers for Redispatch 2.0 XML documents.
2
3use serde::Serialize;
4
5use crate::error::RedispatchXmlError;
6use crate::parse::Document;
7
8// ── Public API ────────────────────────────────────────────────────────────────
9
10/// Serialise a [`Document`] to an XML byte vector.
11///
12/// An `<?xml version="1.0" encoding="UTF-8"?>` declaration is prepended
13/// automatically.
14///
15/// # Errors
16///
17/// Returns [`RedispatchXmlError::Xml`] on serialization failure.
18pub fn serialize(doc: &Document) -> Result<Vec<u8>, RedispatchXmlError> {
19    match doc {
20        Document::Activation(d) => serialize_as(d.as_ref(), true),
21        Document::PlannedResourceSchedule(d) => serialize_as(d.as_ref(), true),
22        Document::Acknowledgement(d) => serialize_as(d.as_ref(), true),
23        Document::Stammdaten(d) => serialize_as(d.as_ref(), true),
24        Document::StatusRequest(d) => serialize_as(d.as_ref(), true),
25        Document::Unavailability(d) => serialize_as(d.as_ref(), true),
26        Document::Kaskade(d) => serialize_as(d.as_ref(), true),
27        Document::NetworkConstraint(d) => serialize_as(d.as_ref(), true),
28        Document::Kostenblatt(d) => serialize_as(d.as_ref(), true),
29    }
30}
31
32/// Serialise a specific document type `T` to an XML byte vector.
33///
34/// # Errors
35///
36/// Returns [`RedispatchXmlError::Xml`] on serialization failure.
37pub fn serialize_as<T: Serialize>(
38    doc: &T,
39    add_xml_decl: bool,
40) -> Result<Vec<u8>, RedispatchXmlError> {
41    let xml_str =
42        quick_xml::se::to_string(doc).map_err(|e| RedispatchXmlError::Serialize(e.to_string()))?;
43    let mut out = Vec::with_capacity(xml_str.len() + 40);
44    if add_xml_decl {
45        out.extend_from_slice(b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
46    }
47    out.extend_from_slice(xml_str.as_bytes());
48    Ok(out)
49}