1use std::collections::hash_map::Entry;
4use std::collections::HashMap;
5use std::fmt::{self};
6use std::mem;
7
8use super::Error;
9use crate::ToXml;
10
11pub struct Serializer<'xml, W: fmt::Write + ?Sized> {
13 output: &'xml mut W,
14 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 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 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 (false, Some(prefix), force_prefix) => {
56 self.output.write_fmt(format_args!("<{prefix}:{name}"))?;
57 if let Some(cx) = &cx {
58 if !force_prefix {
60 self.output
61 .write_fmt(format_args!(" xmlns=\"{}\"", cx.default_ns))?;
62 }
63 }
64 Some(*prefix)
65 }
66 (true, None, _) => {
68 self.output.write_fmt(format_args!("<{name}"))?;
69 None
70 }
71 (true, Some(_), false) => {
73 self.output.write_fmt(format_args!("<{name}"))?;
74 if let Some(cx) = &cx {
76 self.output
77 .write_fmt(format_args!(" xmlns=\"{}\"", cx.default_ns))?;
78 }
79 None
80 }
81 (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 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 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 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 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 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 pub fn prefix(&self, ns: &str) -> Option<&'static str> {
246 self.prefixes.get(ns).copied()
247 }
248
249 pub fn default_ns(&self) -> &'static str {
251 self.default_ns
252 }
253}
254
255#[non_exhaustive]
257pub struct Element<'a, const N: usize> {
258 pub prefix: Option<&'static str>,
260 pub name: &'a str,
262 pub parent: Option<Context<N>>,
264}
265
266#[derive(Debug)]
268#[non_exhaustive]
269pub struct Context<const N: usize> {
270 pub default_ns: &'static str,
272 pub prefixes: [Prefix; N],
274 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#[derive(Clone, Copy, Debug, Default)]
290pub struct Prefix {
291 pub prefix: &'static str,
293 pub ns: &'static str,
295}
296
297#[derive(Debug, Eq, PartialEq)]
298enum State {
299 Attribute,
300 Element,
301 Scalar,
302}