Skip to main content

instant_xml/
ser.rs

1//! XML serialization support code
2
3use std::collections::hash_map::Entry;
4use std::collections::HashMap;
5use std::fmt::{self};
6use std::mem;
7
8use super::Error;
9use crate::ToXml;
10
11/// XML serializer for writing structured XML output
12pub struct Serializer<'xml, W: fmt::Write + ?Sized> {
13    output: &'xml mut W,
14    /// Map namespace keys to prefixes.
15    ///
16    /// The prefix map is updated using `Context` types that are held on the stack in the relevant
17    /// `ToXml` implementation. If a prefix is already defined for a given namespace, we don't
18    /// update the set with the new prefix.
19    prefixes: HashMap<&'static str, &'static str>,
20    default_ns: &'static str,
21    state: State,
22}
23
24impl<'xml, W: fmt::Write + ?Sized> Serializer<'xml, W> {
25    /// Create a new serializer writing to the given output
26    pub fn new(output: &'xml mut W) -> Self {
27        Self {
28            output,
29            prefixes: HashMap::new(),
30            default_ns: "",
31            state: State::Element,
32        }
33    }
34
35    /// Write the opening tag for an element
36    ///
37    /// Returns the namespace prefix if one was used.
38    ///
39    /// The `cx` parameter can be used to specify namespace declarations for the element. When
40    /// passing in `None`, you'll probably need to specify `None::<Context<0>>`.
41    pub fn write_start<'a, const N: usize>(
42        &mut self,
43        name: &'a str,
44        ns: &str,
45        cx: Option<Context<N>>,
46    ) -> Result<Element<'a, N>, Error> {
47        if self.state != State::Element {
48            return Err(Error::UnexpectedState("invalid state for element start"));
49        }
50
51        let force_prefix = cx.as_ref().is_some_and(|cx| cx.force_prefix);
52
53        let prefix = match (ns == self.default_ns, self.prefixes.get(ns), force_prefix) {
54            // Ns != default ns
55            (false, Some(prefix), force_prefix) => {
56                self.output.write_fmt(format_args!("<{prefix}:{name}"))?;
57                if let Some(cx) = &cx {
58                    // Only write the ns as default if not force prefix
59                    if !force_prefix {
60                        self.output
61                            .write_fmt(format_args!(" xmlns=\"{}\"", cx.default_ns))?;
62                    }
63                }
64                Some(*prefix)
65            }
66            // No prefix case
67            (true, None, _) => {
68                self.output.write_fmt(format_args!("<{name}"))?;
69                None
70            }
71            // If ns == default ns and force-prefix is false, we ignore prefix
72            (true, Some(_), false) => {
73                self.output.write_fmt(format_args!("<{name}"))?;
74                // Still requalify the ns here because its not the previous default_ns
75                if let Some(cx) = &cx {
76                    self.output
77                        .write_fmt(format_args!(" xmlns=\"{}\"", cx.default_ns))?;
78                }
79                None
80            }
81            // Force prefix always - when forcing prefix we dont requalify the namespace
82            (true, Some(prefix), true) => {
83                self.output.write_fmt(format_args!("<{prefix}:{name}"))?;
84                Some(*prefix)
85            }
86            _ => {
87                self.output
88                    .write_fmt(format_args!("<{name} xmlns=\"{ns}\""))?;
89                None
90            }
91        };
92
93        self.state = State::Attribute;
94        let Some(cx) = cx else {
95            return Ok(Element {
96                prefix,
97                name,
98                parent: None,
99            });
100        };
101
102        let mut old = Context::default();
103        let prev = mem::replace(&mut self.default_ns, cx.default_ns);
104        let _ = mem::replace(&mut old.default_ns, prev);
105
106        let mut used = 0;
107        for prefix in cx.prefixes.into_iter() {
108            if prefix.prefix.is_empty() {
109                continue;
110            }
111
112            if self.prefixes.contains_key(prefix.ns) {
113                continue;
114            }
115
116            self.output
117                .write_fmt(format_args!(" xmlns:{}=\"{}\"", prefix.prefix, prefix.ns))?;
118
119            let prev = match self.prefixes.entry(prefix.ns) {
120                Entry::Occupied(mut entry) => mem::replace(entry.get_mut(), prefix.prefix),
121                Entry::Vacant(entry) => {
122                    entry.insert(prefix.prefix);
123                    ""
124                }
125            };
126
127            old.prefixes[used] = Prefix {
128                ns: prefix.ns,
129                prefix: prev,
130            };
131            used += 1;
132        }
133
134        Ok(Element {
135            prefix,
136            name,
137            parent: Some(old),
138        })
139    }
140
141    /// Write an attribute with the given name and value
142    pub fn write_attr<V: ToXml + ?Sized>(
143        &mut self,
144        name: &str,
145        ns: &str,
146        value: &V,
147    ) -> Result<(), Error> {
148        if self.state != State::Attribute {
149            return Err(Error::UnexpectedState("invalid state for attribute"));
150        }
151
152        match ns == self.default_ns {
153            true => self.output.write_fmt(format_args!(" {name}=\""))?,
154            false => {
155                let prefix = self
156                    .prefixes
157                    .get(ns)
158                    .ok_or(Error::UnexpectedState("unknown prefix"))?;
159                self.output.write_fmt(format_args!(" {prefix}:{name}=\""))?;
160            }
161        }
162
163        self.state = State::Scalar;
164        value.serialize(None, self)?;
165        self.state = State::Attribute;
166        self.output.write_char('"')?;
167        Ok(())
168    }
169
170    /// Write a string value (text content or attribute value)
171    pub fn write_str<V: fmt::Display + ?Sized>(&mut self, value: &V) -> Result<(), Error> {
172        if !matches!(self.state, State::Element | State::Scalar) {
173            return Err(Error::UnexpectedState("invalid state for scalar"));
174        }
175
176        self.output.write_fmt(format_args!("{value}"))?;
177        self.state = State::Element;
178        Ok(())
179    }
180
181    /// Complete the opening tag and transition to element content
182    pub fn end_start(&mut self) -> Result<(), Error> {
183        if self.state != State::Attribute {
184            return Err(Error::UnexpectedState("invalid state for element end"));
185        }
186
187        self.output.write_char('>')?;
188        self.state = State::Element;
189        Ok(())
190    }
191
192    /// Close an empty element (self-closing tag)
193    pub fn end_empty(&mut self) -> Result<(), Error> {
194        if self.state != State::Attribute {
195            return Err(Error::UnexpectedState("invalid state for element end"));
196        }
197
198        self.output.write_str(" />")?;
199        self.state = State::Element;
200        Ok(())
201    }
202
203    /// Write the closing tag for an element
204    pub fn write_close<const N: usize>(&mut self, element: Element<'_, N>) -> Result<(), Error> {
205        if self.state != State::Element {
206            return Err(Error::UnexpectedState("invalid state for close element"));
207        }
208
209        match element.prefix {
210            Some(prefix) => self
211                .output
212                .write_fmt(format_args!("</{prefix}:{}>", element.name))?,
213            None => self.output.write_fmt(format_args!("</{}>", element.name))?,
214        }
215
216        let Some(old) = element.parent else {
217            return Ok(());
218        };
219
220        let _ = mem::replace(&mut self.default_ns, old.default_ns);
221        for prefix in old.prefixes.into_iter() {
222            if prefix.ns.is_empty() && prefix.prefix.is_empty() {
223                continue;
224            }
225
226            let mut entry = match self.prefixes.entry(prefix.ns) {
227                Entry::Occupied(entry) => entry,
228                Entry::Vacant(_) => unreachable!(),
229            };
230
231            match prefix.prefix {
232                "" => {
233                    entry.remove();
234                }
235                prev => {
236                    let _ = mem::replace(entry.get_mut(), prev);
237                }
238            }
239        }
240
241        Ok(())
242    }
243
244    /// Get the prefix for a namespace URI, if any
245    pub fn prefix(&self, ns: &str) -> Option<&'static str> {
246        self.prefixes.get(ns).copied()
247    }
248
249    /// Get the current default namespace URI
250    pub fn default_ns(&self) -> &'static str {
251        self.default_ns
252    }
253}
254
255/// An element being serialized, used for tracking namespace context
256#[non_exhaustive]
257pub struct Element<'a, const N: usize> {
258    /// Prefix of the element, if any
259    pub prefix: Option<&'static str>,
260    /// Local name of the element
261    pub name: &'a str,
262    /// Namespace context of the parent element, if any
263    pub parent: Option<Context<N>>,
264}
265
266/// Namespace context for serialization
267#[derive(Debug)]
268#[non_exhaustive]
269pub struct Context<const N: usize> {
270    /// The default namespace URI
271    pub default_ns: &'static str,
272    /// Array of namespace prefix mappings
273    pub prefixes: [Prefix; N],
274    /// Force prefix to be included always
275    pub force_prefix: bool,
276}
277
278impl<const N: usize> Default for Context<N> {
279    fn default() -> Self {
280        Self {
281            default_ns: Default::default(),
282            prefixes: [Prefix { prefix: "", ns: "" }; N],
283            force_prefix: false,
284        }
285    }
286}
287
288/// A namespace prefix mapping
289#[derive(Clone, Copy, Debug, Default)]
290pub struct Prefix {
291    /// The namespace prefix
292    pub prefix: &'static str,
293    /// The namespace URI
294    pub ns: &'static str,
295}
296
297#[derive(Debug, Eq, PartialEq)]
298enum State {
299    Attribute,
300    Element,
301    Scalar,
302}