archlinux_repo_parser/
ser.rs

1use serde::{ser, Serialize};
2
3use crate::error::{Error, Result};
4
5pub struct Serializer {
6    output: String,
7}
8
9pub fn to_string<T>(value: &T) -> Result<String>
10where
11    T: Serialize,
12{
13    let mut serializer = Serializer {
14        output: String::new(),
15    };
16    value.serialize(&mut serializer)?;
17    Ok(serializer.output)
18}
19
20impl<'a> ser::Serializer for &'a mut Serializer {
21    type Ok = ();
22    type Error = Error;
23
24    type SerializeSeq = Self;
25    type SerializeTuple = Self;
26    type SerializeTupleStruct = Self;
27    type SerializeTupleVariant = Self;
28    type SerializeMap = Self;
29    type SerializeStruct = Self;
30    type SerializeStructVariant = Self;
31
32    fn serialize_bool(self, _: bool) -> Result<()> {
33        Err(Error::NotSupported)
34    }
35
36    fn serialize_i8(self, v: i8) -> Result<()> {
37        self.serialize_i64(i64::from(v))
38    }
39
40    fn serialize_i16(self, v: i16) -> Result<()> {
41        self.serialize_i64(i64::from(v))
42    }
43
44    fn serialize_i32(self, v: i32) -> Result<()> {
45        self.serialize_i64(i64::from(v))
46    }
47
48    fn serialize_i64(self, v: i64) -> Result<()> {
49        self.output += &v.to_string();
50        Ok(())
51    }
52
53    fn serialize_u8(self, v: u8) -> Result<()> {
54        self.serialize_u64(u64::from(v))
55    }
56
57    fn serialize_u16(self, v: u16) -> Result<()> {
58        self.serialize_u64(u64::from(v))
59    }
60
61    fn serialize_u32(self, v: u32) -> Result<()> {
62        self.serialize_u64(u64::from(v))
63    }
64
65    fn serialize_u64(self, v: u64) -> Result<()> {
66        self.output += &v.to_string();
67        Ok(())
68    }
69
70    fn serialize_f32(self, v: f32) -> Result<()> {
71        self.serialize_f64(f64::from(v))
72    }
73
74    fn serialize_f64(self, _v: f64) -> Result<()> {
75        Err(Error::NotSupported)
76    }
77
78    fn serialize_char(self, v: char) -> Result<()> {
79        self.serialize_str(&v.to_string())
80    }
81
82    fn serialize_str(self, v: &str) -> Result<()> {
83        self.output += v;
84        Ok(())
85    }
86
87    fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
88        Err(Error::NotSupported)
89    }
90
91    fn serialize_none(self) -> Result<()> {
92        self.serialize_unit()
93    }
94
95    fn serialize_some<T>(self, value: &T) -> Result<()>
96    where
97        T: ?Sized + Serialize,
98    {
99        value.serialize(self)
100    }
101
102    fn serialize_unit(self) -> Result<()> {
103        self.output += "\n";
104        Ok(())
105    }
106
107    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
108        self.serialize_unit()
109    }
110
111    fn serialize_unit_variant(
112        self,
113        _name: &'static str,
114        _variant_index: u32,
115        variant: &'static str,
116    ) -> Result<()> {
117        self.serialize_str(variant)
118    }
119
120    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
121    where
122        T: ?Sized + Serialize,
123    {
124        value.serialize(self)
125    }
126
127    fn serialize_newtype_variant<T>(
128        self,
129        _name: &'static str,
130        _variant_index: u32,
131        variant: &'static str,
132        value: &T,
133    ) -> Result<()>
134    where
135        T: ?Sized + Serialize,
136    {
137        self.output += "%";
138        variant.serialize(&mut *self)?;
139        self.output += "%";
140        value.serialize(&mut *self)?;
141        self.output += "\n";
142        Ok(())
143    }
144
145    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
146        Ok(self)
147    }
148
149    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
150        self.serialize_seq(Some(len))
151    }
152
153    fn serialize_tuple_struct(
154        self,
155        _name: &'static str,
156        len: usize,
157    ) -> Result<Self::SerializeTupleStruct> {
158        self.serialize_seq(Some(len))
159    }
160
161    fn serialize_tuple_variant(
162        self,
163        _name: &'static str,
164        _variant_index: u32,
165        _variant: &'static str,
166        _len: usize,
167    ) -> Result<Self::SerializeTupleVariant> {
168        Err(Error::NotSupported)
169    }
170
171    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
172        Ok(self)
173    }
174
175    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
176        self.serialize_map(Some(len))
177    }
178
179    fn serialize_struct_variant(
180        self,
181        _name: &'static str,
182        _variant_index: u32,
183        _variant: &'static str,
184        _len: usize,
185    ) -> Result<Self::SerializeStructVariant> {
186        Err(Error::NotSupported)
187    }
188}
189
190impl<'a> ser::SerializeSeq for &'a mut Serializer {
191    type Ok = ();
192    type Error = Error;
193
194    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
195    where
196        T: ?Sized + Serialize,
197    {
198        value.serialize(&mut **self)?;
199        self.output += "\n";
200        Ok(())
201    }
202
203    fn end(self) -> Result<()> {
204        self.output = self.output[..self.output.len() - 1].to_owned(); // Cut last \n
205        Ok(())
206    }
207}
208
209impl<'a> ser::SerializeTuple for &'a mut Serializer {
210    type Ok = ();
211    type Error = Error;
212
213    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
214    where
215        T: ?Sized + Serialize,
216    {
217        value.serialize(&mut **self)?;
218        self.output += "\n";
219        Ok(())
220    }
221
222    fn end(self) -> Result<()> {
223        self.output = self.output[..self.output.len() - 1].to_owned(); // Cut last \n
224        Ok(())
225    }
226}
227
228impl<'a> ser::SerializeTupleStruct for &'a mut Serializer {
229    type Ok = ();
230    type Error = Error;
231
232    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
233    where
234        T: ?Sized + Serialize,
235    {
236        value.serialize(&mut **self)?;
237        self.output += "\n";
238        Ok(())
239    }
240
241    fn end(self) -> Result<()> {
242        self.output = self.output[..self.output.len() - 1].to_owned(); // Cut last \n
243        Ok(())
244    }
245}
246
247impl<'a> ser::SerializeTupleVariant for &'a mut Serializer {
248    type Ok = ();
249    type Error = Error;
250
251    fn serialize_field<T>(&mut self, _: &T) -> Result<()>
252    where
253        T: ?Sized + Serialize,
254    {
255        Err(Error::NotSupported)
256    }
257
258    fn end(self) -> Result<()> {
259        Err(Error::NotSupported)
260    }
261}
262
263impl<'a> ser::SerializeMap for &'a mut Serializer {
264    type Ok = ();
265    type Error = Error;
266
267    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
268    where
269        T: ?Sized + Serialize,
270    {
271        self.output += "%";
272        key.serialize(&mut **self)?;
273        self.output += "%";
274        Ok(())
275    }
276
277    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
278    where
279        T: ?Sized + Serialize,
280    {
281        self.output += "\n";
282        value.serialize(&mut **self)?;
283        self.output += "\n";
284        self.output += "\n";
285        Ok(())
286    }
287
288    fn end(self) -> Result<()> {
289        Ok(())
290    }
291}
292
293impl<'a> ser::SerializeStruct for &'a mut Serializer {
294    type Ok = ();
295    type Error = Error;
296
297    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
298    where
299        T: ?Sized + Serialize,
300    {
301        self.output += "%";
302        key.serialize(&mut **self)?;
303        self.output += "%";
304        self.output += "\n";
305        value.serialize(&mut **self)?;
306        self.output += "\n";
307        self.output += "\n";
308        Ok(())
309    }
310
311    fn end(self) -> Result<()> {
312        Ok(())
313    }
314}
315
316// Similar to `SerializeTupleVariant`, here the `end` method is responsible for
317// closing both of the curly braces opened by `serialize_struct_variant`.
318impl<'a> ser::SerializeStructVariant for &'a mut Serializer {
319    type Ok = ();
320    type Error = Error;
321
322    fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<()>
323    where
324        T: ?Sized + Serialize,
325    {
326        Err(Error::NotSupported)
327    }
328
329    fn end(self) -> Result<()> {
330        Err(Error::NotSupported)
331    }
332}
333
334#[cfg(test)]
335mod test {
336    use serde::Serialize;
337
338    #[test]
339    fn test_struct() {
340        #[derive(Serialize, PartialEq, Debug)]
341        struct Test {
342            #[serde(rename = "NAME")]
343            name: String,
344            #[serde(rename = "BUILDDATE")]
345            build_date: u32,
346            #[serde(rename = "DEPENDS")]
347            depends: Vec<String>,
348        }
349
350        let j = r#"%NAME%
351mingw-w64-x86_64-vcdimager
352
353%BUILDDATE%
3541592300880
355
356%DEPENDS%
357mingw-w64-x86_64-libcdio
358mingw-w64-x86_64-libxml2
359mingw-w64-x86_64-popt
360
361"#;
362        let val = Test {
363            build_date: 1592300880,
364            depends: vec![
365                "mingw-w64-x86_64-libcdio".to_owned(),
366                "mingw-w64-x86_64-libxml2".to_owned(),
367                "mingw-w64-x86_64-popt".to_owned(),
368            ],
369            name: "mingw-w64-x86_64-vcdimager".to_owned(),
370        };
371        assert_eq!(crate::to_string(&val).unwrap(), j);
372    }
373}