xml_rpc/xmlfmt/
ser.rs

1use super::error::{Error, ErrorKind};
2use super::Value;
3use serde::{self, Serialize};
4use std::collections::HashMap;
5
6pub struct Serializer;
7
8impl serde::Serializer for Serializer {
9    type Ok = Value;
10    type Error = Error;
11
12    type SerializeSeq = SerializeVec;
13    type SerializeTuple = SerializeVec;
14    type SerializeTupleStruct = SerializeVec;
15    type SerializeTupleVariant = SerializeVec;
16    type SerializeMap = SerializeMap;
17    type SerializeStruct = SerializeMap;
18    type SerializeStructVariant = SerializeMap;
19
20    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
21        Ok(Value::Bool(v))
22    }
23
24    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
25        Ok(Value::Int(i32::from(v)))
26    }
27
28    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
29        Ok(Value::Int(i32::from(v)))
30    }
31
32    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
33        Ok(Value::Int(v))
34    }
35
36    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
37        Ok(Value::String(v.to_string()))
38    }
39
40    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
41        Ok(Value::Int(i32::from(v)))
42    }
43
44    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
45        Ok(Value::Int(i32::from(v)))
46    }
47
48    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
49        Ok(Value::String(v.to_string()))
50    }
51
52    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
53        Ok(Value::String(v.to_string()))
54    }
55
56    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
57        Ok(Value::Double(f64::from(v)))
58    }
59
60    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
61        Ok(Value::Double(v))
62    }
63
64    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
65        Ok(Value::String(v.to_string()))
66    }
67
68    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
69        Ok(Value::String(v.into()))
70    }
71
72    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
73        Ok(Value::Base64(v.into()))
74    }
75
76    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
77        Ok(Value::Array(Vec::new()))
78    }
79
80    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
81    where
82        T: Serialize + ?Sized,
83    {
84        Ok(Value::Array(vec![value.serialize(self)?]))
85    }
86
87    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
88        Ok(Value::Struct(HashMap::new()))
89    }
90
91    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
92        self.serialize_unit()
93    }
94
95    fn serialize_unit_variant(
96        self,
97        _name: &'static str,
98        _variant_index: u32,
99        variant: &'static str,
100    ) -> Result<Self::Ok, Self::Error> {
101        let mut members = HashMap::new();
102        members.insert(variant.into(), self.serialize_unit()?);
103        Ok(Value::Struct(members))
104    }
105
106    fn serialize_newtype_struct<T>(
107        self,
108        _name: &'static str,
109        value: &T,
110    ) -> Result<Self::Ok, Self::Error>
111    where
112        T: Serialize + ?Sized,
113    {
114        value.serialize(self)
115    }
116
117    fn serialize_newtype_variant<T>(
118        self,
119        _name: &'static str,
120        _variant_index: u32,
121        variant: &'static str,
122        value: &T,
123    ) -> Result<Self::Ok, Self::Error>
124    where
125        T: Serialize + ?Sized,
126    {
127        let mut members = HashMap::new();
128        members.insert(variant.into(), value.serialize(self)?);
129        Ok(Value::Struct(members))
130    }
131
132    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
133        self.serialize_tuple(len.unwrap_or(0))
134    }
135
136    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
137        Ok(SerializeVec {
138            vec: Vec::with_capacity(len),
139            variant: None,
140        })
141    }
142
143    fn serialize_tuple_struct(
144        self,
145        _name: &'static str,
146        len: usize,
147    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
148        self.serialize_tuple(len)
149    }
150
151    fn serialize_tuple_variant(
152        self,
153        _name: &'static str,
154        _variant_index: u32,
155        variant: &'static str,
156        len: usize,
157    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
158        Ok(SerializeVec {
159            vec: Vec::with_capacity(len),
160            variant: Some(variant.into()),
161        })
162    }
163
164    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
165        Ok(SerializeMap {
166            map: HashMap::new(),
167            next_key: None,
168            variant: None,
169        })
170    }
171
172    fn serialize_struct(
173        self,
174        _name: &'static str,
175        len: usize,
176    ) -> Result<Self::SerializeStruct, Self::Error> {
177        self.serialize_map(Some(len))
178    }
179
180    fn serialize_struct_variant(
181        self,
182        _name: &'static str,
183        _variant_index: u32,
184        variant: &'static str,
185        _len: usize,
186    ) -> Result<Self::SerializeStructVariant, Self::Error> {
187        Ok(SerializeMap {
188            map: HashMap::new(),
189            next_key: None,
190            variant: Some(variant.into()),
191        })
192    }
193}
194
195fn to_value<T>(value: &T) -> Result<Value, Error>
196where
197    T: Serialize,
198{
199    value.serialize(Serializer)
200}
201
202#[doc(hidden)]
203pub struct SerializeVec {
204    vec: Vec<Value>,
205    variant: Option<String>,
206}
207
208impl serde::ser::SerializeSeq for SerializeVec {
209    type Ok = Value;
210    type Error = Error;
211
212    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
213    where
214        T: Serialize + ?Sized,
215    {
216        self.vec.push(to_value(&value)?);
217        Ok(())
218    }
219
220    fn end(self) -> Result<Value, Error> {
221        let content = Value::Array(self.vec);
222        Ok(match self.variant {
223            Some(variant) => {
224                let mut members = HashMap::new();
225                members.insert(variant, content);
226                Value::Struct(members)
227            }
228            None => content,
229        })
230    }
231}
232
233impl serde::ser::SerializeTuple for SerializeVec {
234    type Ok = Value;
235    type Error = Error;
236
237    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
238    where
239        T: Serialize + ?Sized,
240    {
241        serde::ser::SerializeSeq::serialize_element(self, value)
242    }
243
244    fn end(self) -> Result<Value, Error> {
245        serde::ser::SerializeSeq::end(self)
246    }
247}
248
249impl serde::ser::SerializeTupleStruct for SerializeVec {
250    type Ok = Value;
251    type Error = Error;
252
253    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
254    where
255        T: Serialize + ?Sized,
256    {
257        serde::ser::SerializeSeq::serialize_element(self, value)
258    }
259
260    fn end(self) -> Result<Value, Error> {
261        serde::ser::SerializeSeq::end(self)
262    }
263}
264
265impl serde::ser::SerializeTupleVariant for SerializeVec {
266    type Ok = Value;
267    type Error = Error;
268
269    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
270    where
271        T: Serialize + ?Sized,
272    {
273        serde::ser::SerializeSeq::serialize_element(self, value)
274    }
275
276    fn end(self) -> Result<Value, Error> {
277        serde::ser::SerializeSeq::end(self)
278    }
279}
280
281#[doc(hidden)]
282pub struct SerializeMap {
283    map: HashMap<String, Value>,
284    next_key: Option<String>,
285    variant: Option<String>,
286}
287
288impl serde::ser::SerializeMap for SerializeMap {
289    type Ok = Value;
290    type Error = Error;
291
292    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>
293    where
294        T: Serialize + ?Sized,
295    {
296        match to_value(&key)? {
297            Value::Bool(v) => self.next_key = Some(v.to_string()),
298            Value::Int(v) => self.next_key = Some(v.to_string()),
299            Value::Double(v) => self.next_key = Some(v.to_string()),
300            Value::String(s) => self.next_key = Some(s),
301            _ => bail!(ErrorKind::UnsupportedData(
302                "Key must be a bool, int, float, char or string.".into(),
303            )),
304        };
305        Ok(())
306    }
307
308    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
309    where
310        T: Serialize + ?Sized,
311    {
312        let key = self.next_key.take();
313        // Panic because this indicates a bug in the program rather than an
314        // expected failure.
315        let key = key.expect("serialize_value called before serialize_key");
316        self.map.insert(key, to_value(&value)?);
317        Ok(())
318    }
319
320    fn end(self) -> Result<Value, Error> {
321        let content = Value::Struct(self.map);
322        Ok(match self.variant {
323            Some(variant) => {
324                let mut members = HashMap::new();
325                members.insert(variant, content);
326                Value::Struct(members)
327            }
328            None => content,
329        })
330    }
331}
332
333impl serde::ser::SerializeStruct for SerializeMap {
334    type Ok = Value;
335    type Error = Error;
336
337    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
338    where
339        T: Serialize + ?Sized,
340    {
341        serde::ser::SerializeMap::serialize_key(self, key)?;
342        serde::ser::SerializeMap::serialize_value(self, value)
343    }
344
345    fn end(self) -> Result<Value, Error> {
346        serde::ser::SerializeMap::end(self)
347    }
348}
349
350impl serde::ser::SerializeStructVariant for SerializeMap {
351    type Ok = Value;
352    type Error = Error;
353
354    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
355    where
356        T: Serialize + ?Sized,
357    {
358        serde::ser::SerializeMap::serialize_key(self, key)?;
359        serde::ser::SerializeMap::serialize_value(self, value)
360    }
361
362    fn end(self) -> Result<Value, Error> {
363        serde::ser::SerializeMap::end(self)
364    }
365}