serde_xml_rs2/ser/
mod.rs

1extern crate xmltree;
2
3use error::{Error, ErrorKind, Result};
4use serde::ser::{self, Serialize};
5
6use std::io::Write;
7use std::collections::BTreeMap;
8
9mod primitive_serializer;
10
11/// A convenience method for serializing some object to a buffer.
12///
13/// # Examples
14///
15/// ```rust
16/// # #[macro_use]
17/// # extern crate serde_derive;
18/// # extern crate serde;
19/// # extern crate serde_xml_rs;
20/// # use serde_xml_rs::to_writer;
21/// #[derive(Serialize)]
22/// struct Person {
23///   name: String,
24///   age: u32,
25/// }
26///
27/// # fn main() {
28/// let mut buffer = Vec::new();
29/// let joe = Person {name: "Joe".to_string(), age: 42};
30///
31/// to_writer(&mut buffer, &joe).unwrap();
32///
33/// let serialized = String::from_utf8(buffer).unwrap();
34/// println!("{}", serialized);
35/// # }
36/// ```
37pub fn to_writer<W: Write, S: Serialize>(writer: W, value: &S) -> Result<()> {
38    let mut serializer = Serializer::new();
39    value.serialize(&mut serializer)?;
40    let ref tree = serializer.current_path[0];
41    tree.write(writer);
42    Ok(())
43}
44
45/// A convenience method for serializing some object to a string.
46///
47/// # Examples
48///
49/// ```rust
50/// # #[macro_use]
51/// # extern crate serde_derive;
52/// # extern crate serde;
53/// # extern crate serde_xml_rs;
54/// # use serde_xml_rs::to_string;
55/// #[derive(Serialize)]
56/// struct Person {
57///   name: String,
58///   age: u32,
59/// }
60///
61/// # fn main() {
62///
63/// let joe = Person {name: "Joe".to_string(), age: 42};
64/// let serialized = to_string(&joe).unwrap();
65/// println!("{}", serialized);
66/// # }
67/// ```
68pub fn to_string<S: Serialize>(value: &S) -> Result<String> {
69    let mut buffer = Vec::new();
70    to_writer(&mut buffer, value)?;
71    let result = String::from_utf8(buffer).unwrap();
72    Ok(result)
73}
74
75/// A convenience method for serializing some object to a string, with
76/// xml namespaces.
77///
78/// # Examples
79///
80/// ```rust
81/// # #[macro_use]
82/// # extern crate serde_derive;
83/// # extern crate serde;
84/// # extern crate serde_xml_rs;
85/// # use serde_xml_rs::to_string_with_namespaces;
86/// # use std::collections::BTreeMap;
87/// #[derive(Serialize)]
88/// struct Person {
89///   name: String,
90///   age: u32,
91/// }
92///
93/// # fn main() {
94/// let mut namespaces = BTreeMap::new();
95/// namespaces.insert("".to_string(), "http://example.com/schema.xsd".to_string());
96/// let joe = Person {name: "Joe".to_string(), age: 42};
97/// // An empty key indicates a global namespace
98/// let serialized = to_string_with_namespaces(&joe, namespaces).unwrap();
99/// println!("{}", serialized);
100/// # }
101/// ```
102pub fn to_string_with_namespaces<S: Serialize>(
103    value: &S,
104    namespaces: BTreeMap<String, String>,
105) -> Result<String> {
106    let mut serializer = Serializer::new();
107    value.serialize(&mut serializer)?;
108
109    let mut buffer = Vec::new();
110    let ref mut tree = serializer.current_path[0];
111
112    let namespaces = xmltree::Namespace(namespaces);
113    tree.namespaces = Some(namespaces);
114
115    tree.write(&mut buffer);
116    let result = String::from_utf8(buffer).unwrap();
117    Ok(result)
118}
119
120pub struct Serializer {
121    // holds a list of elements from the root node down
122    // to the element we're currently serializing.
123    pub current_path: Vec<xmltree::Element>,
124    serialize_names: bool,
125    serializing_name: bool,
126    first_struct: bool,
127}
128
129impl Serializer {
130    pub fn new() -> Serializer {
131        Serializer {
132            current_path: Vec::new(),
133            serialize_names: false,
134            serializing_name: true,
135            first_struct: true,
136        }
137    }
138
139    // Take the last element off current_path and make it a child
140    // of the new last element in current_path.
141    fn pop_current_path(&mut self) {
142        let child_element = self.current_path.pop().unwrap();
143        let parent_element = self.current_path.pop();
144        if let Some(mut parent) = parent_element {
145            parent.children.push(child_element);
146            self.current_path.push(parent);
147        } else {
148            self.current_path.push(child_element);
149        }
150    }
151
152    // Make sure we serialize item names if we're in a sequence.
153    fn serialize_item_name_if_wrapped(&mut self, name: &str) {
154        if self.serialize_names || self.first_struct {
155            self.first_struct = false;
156            self.serializing_name = true;
157            let name_element = xmltree::Element::new(name);
158            self.current_path.push(name_element);
159        }
160    }
161
162    fn pop_current_path_if_wrapped(&mut self) {
163        if self.serializing_name {
164            self.serializing_name = false;
165            self.pop_current_path();
166        }
167    }
168}
169
170
171impl<'a> ser::Serializer for &'a mut Serializer {
172    type Ok = ();
173    type Error = Error;
174
175    type SerializeSeq = Self;
176    type SerializeTuple = Self;
177    type SerializeTupleStruct = Self;
178    type SerializeTupleVariant = Self;
179    type SerializeMap = Self;
180    type SerializeStruct = Self;
181    type SerializeStructVariant = Self;
182
183    fn serialize_bool(self, v: bool) -> Result<Self::Ok> {
184        let mut element = self.current_path.pop().unwrap();
185        if v {
186            element.text = Some("true".to_string())
187        } else {
188            element.text = Some("false".to_string())
189        }
190        self.current_path.push(element);
191        Ok(())
192    }
193
194    fn serialize_i8(self, v: i8) -> Result<Self::Ok> {
195        self.serialize_i64(v as i64)
196    }
197
198    fn serialize_i16(self, v: i16) -> Result<Self::Ok> {
199        self.serialize_i64(v as i64)
200    }
201
202    fn serialize_i32(self, v: i32) -> Result<Self::Ok> {
203        self.serialize_i64(v as i64)
204    }
205
206    fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
207        let mut element = self.current_path.pop().unwrap();
208        element.text = Some(v.to_string());
209        self.current_path.push(element);
210        Ok(())
211    }
212
213    fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
214        self.serialize_u64(v as u64)
215    }
216
217    fn serialize_u16(self, v: u16) -> Result<Self::Ok> {
218        self.serialize_u64(v as u64)
219    }
220
221    fn serialize_u32(self, v: u32) -> Result<Self::Ok> {
222        self.serialize_u64(v as u64)
223    }
224
225    fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
226        let mut element = self.current_path.pop().unwrap();
227        element.text = Some(v.to_string());
228        self.current_path.push(element);
229        Ok(())
230    }
231
232    fn serialize_f32(self, v: f32) -> Result<Self::Ok> {
233        self.serialize_f64(v as f64)
234    }
235
236    fn serialize_f64(self, v: f64) -> Result<Self::Ok> {
237        let mut element = self.current_path.pop().unwrap();
238        element.text = Some(v.to_string());
239        self.current_path.push(element);
240        Ok(())
241    }
242
243    // Serialize a char as a single-character string.
244    fn serialize_char(self, v: char) -> Result<Self::Ok> {
245        self.serialize_str(&v.to_string())
246    }
247
248    fn serialize_str(self, v: &str) -> Result<Self::Ok> {
249        let mut element = self.current_path.pop().unwrap();
250        element.text = Some(v.to_string());
251        self.current_path.push(element);
252        Ok(())
253    }
254
255    fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok> {
256        Err(
257            ErrorKind::UnsupportedOperation("serialize_bytes".to_string()).into(),
258        )
259    }
260
261    // An absent optional is represented with an empty element.
262    fn serialize_none(self) -> Result<Self::Ok> {
263        Ok(())
264    }
265
266    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok>
267    where
268        T: ?Sized + Serialize,
269    {
270        value.serialize(self)
271    }
272
273    fn serialize_unit(self) -> Result<Self::Ok> {
274        Ok(())
275    }
276
277    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
278        self.serialize_unit()
279    }
280
281    // Represent unit variants as value
282    fn serialize_unit_variant(
283        self,
284        _name: &'static str,
285        _variant_index: u32,
286        variant: &'static str,
287    ) -> Result<Self::Ok> {
288        self.serialize_str(variant)?;
289        Ok(())
290    }
291
292    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Self::Ok>
293    where
294        T: ?Sized + Serialize,
295    {
296        value.serialize(self)
297    }
298
299    // Represent E::N(a) as <N>a</N>
300    fn serialize_newtype_variant<T>(
301        self,
302        _name: &'static str,
303        _variant_index: u32,
304        variant: &'static str,
305        value: &T,
306    ) -> Result<Self::Ok>
307    where
308        T: ?Sized + Serialize,
309    {
310        let variant_element = xmltree::Element::new(variant);
311        self.current_path.push(variant_element);
312        value.serialize(&mut *self)?;
313        self.pop_current_path();
314        Ok(())
315    }
316
317    // We want to wrap each element in a sequence in the name of its parent type, so turn
318    // on serialization of the type names. For example, vec[]
319    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
320        self.serialize_names = true;
321        Ok(self)
322    }
323
324    // Tuples look just like sequences in XML.
325    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
326        self.serialize_seq(Some(len))
327    }
328
329    // Ditto for tuple structs, but serialize the name.
330    fn serialize_tuple_struct(
331        self,
332        name: &'static str,
333        len: usize,
334    ) -> Result<Self::SerializeTupleStruct> {
335        let name_element = xmltree::Element::new(name);
336        self.current_path.push(name_element);
337        self.serialize_seq(Some(len))?;
338        self.pop_current_path();
339        Ok(self)
340    }
341
342    // Tuple variants are represented as <name>sequence of data</name>
343    fn serialize_tuple_variant(
344        self,
345        name: &'static str,
346        _variant_index: u32,
347        variant: &'static str,
348        _len: usize,
349    ) -> Result<Self::SerializeTupleVariant> {
350        let name_element = xmltree::Element::new(name);
351        self.current_path.push(name_element);
352        variant.serialize(&mut *self)?;
353        self.pop_current_path();
354        Ok(self)
355    }
356
357    // Maps are represented as <k>v</k><k>v</k>... So nothing is done here, but is handled
358    // in the SerializeMap impl below.
359    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
360        Ok(self)
361    }
362
363    // Structs look just like maps in xml.
364    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
365        self.serialize_item_name_if_wrapped(name);
366        self.serialize_map(Some(len))
367    }
368
369    fn serialize_struct_variant(
370        self,
371        _name: &'static str,
372        _variant_index: u32,
373        variant: &'static str,
374        _len: usize,
375    ) -> Result<Self::SerializeStructVariant> {
376        let name_element = xmltree::Element::new(variant);
377        self.current_path.push(name_element);
378        // variant.serialize(&mut *self)?;
379        Ok(self)
380    }
381}
382
383// The following 7 impls deal with the serialization of compound types like
384// sequences and maps. Serialization of such types is begun by a Serializer
385// method and followed by zero or more calls to serialize individual elements of
386// the compound type and one call to end the compound type.
387//
388// This impl is SerializeSeq so these methods are called after `serialize_seq`
389// is called on the Serializer.
390impl<'a> ser::SerializeSeq for &'a mut Serializer {
391    // Must match the `Ok` type of the serializer.
392    type Ok = ();
393    // Must match the `Error` type of the serializer.
394    type Error = Error;
395
396    // Serialize a single element of the sequence.
397    fn serialize_element<T>(&mut self, value: &T) -> Result<Self::Ok>
398    where
399        T: ?Sized + Serialize,
400    {
401        value.serialize(&mut **self)
402    }
403
404    // Close the sequence.
405    fn end(self) -> Result<Self::Ok> {
406        self.serialize_names = false;
407        Ok(())
408    }
409}
410
411// Same thing but for tuples.
412impl<'a> ser::SerializeTuple for &'a mut Serializer {
413    type Ok = ();
414    type Error = Error;
415
416    fn serialize_element<T>(&mut self, value: &T) -> Result<Self::Ok>
417    where
418        T: ?Sized + Serialize,
419    {
420        value.serialize(&mut **self)
421    }
422
423    fn end(self) -> Result<Self::Ok> {
424        Ok(())
425    }
426}
427
428// Same thing but for tuple structs.
429impl<'a> ser::SerializeTupleStruct for &'a mut Serializer {
430    type Ok = ();
431    type Error = Error;
432
433    fn serialize_field<T>(&mut self, value: &T) -> Result<Self::Ok>
434    where
435        T: ?Sized + Serialize,
436    {
437        value.serialize(&mut **self)
438    }
439
440    fn end(self) -> Result<Self::Ok> {
441        self.pop_current_path();
442        Ok(())
443    }
444}
445
446impl<'a> ser::SerializeTupleVariant for &'a mut Serializer {
447    type Ok = ();
448    type Error = Error;
449
450    fn serialize_field<T>(&mut self, value: &T) -> Result<Self::Ok>
451    where
452        T: ?Sized + Serialize,
453    {
454        value.serialize(&mut **self)
455    }
456
457    fn end(self) -> Result<Self::Ok> {
458        self.pop_current_path();
459        Ok(())
460    }
461}
462
463impl<'a> ser::SerializeMap for &'a mut Serializer {
464    type Ok = ();
465    type Error = Error;
466
467    // XML only allows for keys to be strings, so we use a special serializer
468    // which only accepts str below.
469    fn serialize_key<T>(&mut self, key: &T) -> Result<Self::Ok>
470    where
471        T: ?Sized + Serialize,
472    {
473        let name = primitive_serializer::serialize_primitive(key)?;
474        let key_element = xmltree::Element::new(&name);
475        self.current_path.push(key_element);
476        Ok(())
477    }
478
479
480    fn serialize_value<T>(&mut self, value: &T) -> Result<Self::Ok>
481    where
482        T: ?Sized + Serialize,
483    {
484        value.serialize(&mut **self)?;
485        self.pop_current_path();
486        Ok(())
487    }
488
489    fn end(self) -> Result<Self::Ok> {
490        Ok(())
491    }
492}
493
494// Structs are like maps in which the keys are constrained to be compile-time
495// constant strings.
496impl<'a> ser::SerializeStruct for &'a mut Serializer {
497    type Ok = ();
498    type Error = Error;
499
500    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<Self::Ok>
501    where
502        T: ?Sized + Serialize,
503    {
504        let element = xmltree::Element::new(key);
505        self.current_path.push(element);
506        value.serialize(&mut **self)?;
507        self.pop_current_path();
508        Ok(())
509    }
510
511    fn end(self) -> Result<Self::Ok> {
512        self.pop_current_path_if_wrapped();
513        Ok(())
514    }
515}
516
517impl<'a> ser::SerializeStructVariant for &'a mut Serializer {
518    type Ok = ();
519    type Error = Error;
520
521    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<Self::Ok>
522    where
523        T: ?Sized + Serialize,
524    {
525        let element = xmltree::Element::new(key);
526        self.current_path.push(element);
527        value.serialize(&mut **self)?;
528        self.pop_current_path();
529        Ok(())
530    }
531
532    fn end(self) -> Result<Self::Ok> {
533        self.pop_current_path();
534        Ok(())
535    }
536}