rmpv/ext/
se.rs

1use std::fmt::Display;
2
3use serde::Serialize;
4use serde::ser::{self, SerializeTupleStruct, SerializeSeq, SerializeTuple, SerializeMap, SerializeStruct};
5use serde_bytes::Bytes;
6
7use crate::{Integer, IntPriv, Value};
8
9use super::Error;
10use crate::MSGPACK_EXT_STRUCT_NAME;
11
12impl Serialize for Value {
13    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
14        where S: ser::Serializer
15    {
16        match *self {
17            Value::Nil => s.serialize_unit(),
18            Value::Boolean(v) => s.serialize_bool(v),
19            Value::Integer(Integer { n }) => {
20                match n {
21                    IntPriv::PosInt(n) => s.serialize_u64(n),
22                    IntPriv::NegInt(n) => s.serialize_i64(n),
23                }
24            }
25            Value::F32(v) => s.serialize_f32(v),
26            Value::F64(v) => s.serialize_f64(v),
27            Value::String(ref v) => {
28                match v.s {
29                    Ok(ref v) => s.serialize_str(v),
30                    Err(ref v) => Bytes::new(&v.0[..]).serialize(s),
31                }
32            }
33            Value::Binary(ref v) => Bytes::new(&v[..]).serialize(s),
34            Value::Array(ref array) => {
35                let mut state = s.serialize_seq(Some(array.len()))?;
36                for item in array {
37                    state.serialize_element(item)?;
38                }
39                state.end()
40            }
41            Value::Map(ref map) => {
42                let mut state = s.serialize_map(Some(map.len()))?;
43                for &(ref key, ref val) in map {
44                    state.serialize_entry(key, val)?;
45                }
46                state.end()
47            }
48            Value::Ext(ty, ref buf) => {
49                let value = (ty, Bytes::new(&buf[..]));
50                s.serialize_newtype_struct(MSGPACK_EXT_STRUCT_NAME, &value)
51            }
52        }
53    }
54}
55
56impl ser::Error for Error {
57    fn custom<T: Display>(msg: T) -> Self {
58        Error::Syntax(format!("{}", msg))
59    }
60}
61
62struct Serializer;
63
64/// Convert a `T` into `rmpv::Value` which is an enum that can represent any valid MessagePack data.
65///
66/// This conversion can fail if `T`'s implementation of `Serialize` decides to fail.
67///
68/// ```rust
69/// # use rmpv::Value;
70///
71/// let val = rmpv::ext::to_value("John Smith").unwrap();
72///
73/// assert_eq!(Value::String("John Smith".into()), val);
74/// ```
75pub fn to_value<T: Serialize>(value: T) -> Result<Value, Error> {
76    value.serialize(Serializer)
77}
78
79impl ser::Serializer for Serializer {
80    type Ok = Value;
81    type Error = Error;
82
83    type SerializeSeq = SerializeVec;
84    type SerializeTuple = SerializeVec;
85    type SerializeTupleStruct = SerializeVec;
86    type SerializeTupleVariant = SerializeTupleVariant;
87    type SerializeMap = DefaultSerializeMap;
88    type SerializeStruct = SerializeVec;
89    type SerializeStructVariant = SerializeStructVariant;
90
91    #[inline]
92    fn serialize_bool(self, val: bool) -> Result<Self::Ok, Self::Error> {
93        Ok(Value::Boolean(val))
94    }
95
96    #[inline]
97    fn serialize_i8(self, val: i8) -> Result<Self::Ok, Self::Error> {
98        self.serialize_i64(val as i64)
99    }
100
101    #[inline]
102    fn serialize_i16(self, val: i16) -> Result<Self::Ok, Self::Error> {
103        self.serialize_i64(val as i64)
104    }
105
106    #[inline]
107    fn serialize_i32(self, val: i32) -> Result<Self::Ok, Self::Error> {
108        self.serialize_i64(val as i64)
109    }
110
111    #[inline]
112    fn serialize_i64(self, val: i64) -> Result<Self::Ok, Self::Error> {
113        Ok(Value::from(val))
114    }
115
116    #[inline]
117    fn serialize_u8(self, val: u8) -> Result<Self::Ok, Self::Error> {
118        self.serialize_u64(val as u64)
119    }
120
121    #[inline]
122    fn serialize_u16(self, val: u16) -> Result<Self::Ok, Self::Error> {
123        self.serialize_u64(val as u64)
124    }
125
126    #[inline]
127    fn serialize_u32(self, val: u32) -> Result<Self::Ok, Self::Error> {
128        self.serialize_u64(val as u64)
129    }
130
131    #[inline]
132    fn serialize_u64(self, val: u64) -> Result<Self::Ok, Self::Error> {
133        Ok(Value::from(val))
134    }
135
136    #[inline]
137    fn serialize_f32(self, val: f32) -> Result<Self::Ok, Self::Error> {
138        Ok(Value::F32(val))
139    }
140
141    #[inline]
142    fn serialize_f64(self, val: f64) -> Result<Self::Ok, Self::Error> {
143        Ok(Value::F64(val))
144    }
145
146    #[inline]
147    fn serialize_char(self, val: char) -> Result<Self::Ok, Self::Error> {
148        let mut buf = String::new();
149        buf.push(val);
150        self.serialize_str(&buf)
151    }
152
153    #[inline]
154    fn serialize_str(self, val: &str) -> Result<Self::Ok, Self::Error> {
155        Ok(Value::String(val.into()))
156    }
157
158    #[inline]
159    fn serialize_bytes(self, val: &[u8]) -> Result<Self::Ok, Self::Error> {
160        Ok(Value::Binary(val.into()))
161    }
162
163    #[inline]
164    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
165        Ok(Value::Nil)
166    }
167
168    #[inline]
169    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
170        Ok(Value::Array(Vec::new()))
171    }
172
173    #[inline]
174    fn serialize_unit_variant(self, _name: &'static str, idx: u32, _variant: &'static str) -> Result<Self::Ok, Self::Error> {
175        let vec = vec![
176            Value::from(idx),
177            Value::Array(Vec::new())
178        ];
179        Ok(Value::Array(vec))
180    }
181
182    #[inline]
183    fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
184        where T: Serialize
185    {
186        if name == MSGPACK_EXT_STRUCT_NAME {
187            let mut ext_se = ExtSerializer::new();
188            value.serialize(&mut ext_se)?;
189
190            return ext_se.value();
191        }
192
193        to_value(value)
194    }
195
196    fn serialize_newtype_variant<T: ?Sized>(self, _name: &'static str, idx: u32, _variant: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
197        where T: Serialize
198    {
199        let vec = vec![
200            Value::from(idx),
201            Value::Array(vec![to_value(value)?]),
202        ];
203        Ok(Value::Array(vec))
204    }
205
206    #[inline]
207    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
208        self.serialize_unit()
209    }
210
211    #[inline]
212    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
213        where T: Serialize
214    {
215        value.serialize(self)
216    }
217
218    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
219        let se = SerializeVec {
220            vec: Vec::with_capacity(len.unwrap_or(0))
221        };
222        Ok(se)
223    }
224
225    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> {
226        self.serialize_seq(Some(len))
227    }
228
229    fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct, Error> {
230        self.serialize_tuple(len)
231    }
232
233    fn serialize_tuple_variant(self, _name: &'static str, idx: u32, _variant: &'static str, len: usize) -> Result<Self::SerializeTupleVariant, Error> {
234        let se = SerializeTupleVariant {
235            idx: idx,
236            vec: Vec::with_capacity(len),
237        };
238        Ok(se)
239    }
240
241    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Error> {
242        let se = DefaultSerializeMap {
243            map: Vec::with_capacity(len.unwrap_or(0)),
244            next_key: None,
245        };
246        Ok(se)
247    }
248
249    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, Error> {
250        self.serialize_tuple_struct(name, len)
251    }
252
253    fn serialize_struct_variant(self, _name: &'static str, idx: u32, _variant: &'static str, len: usize) -> Result<Self::SerializeStructVariant, Error> {
254        let se = SerializeStructVariant {
255            idx: idx,
256            vec: Vec::with_capacity(len),
257        };
258        Ok(se)
259    }
260}
261
262pub struct ExtSerializer {
263    fields_se: Option<ExtFieldSerializer>
264}
265
266impl ser::Serializer for &mut ExtSerializer {
267    type Ok = ();
268    type Error = Error;
269
270    type SerializeSeq = ser::Impossible<(), Error>;
271    type SerializeTuple = Self;
272    type SerializeTupleStruct = ser::Impossible<(), Error>;
273    type SerializeTupleVariant = ser::Impossible<(), Error>;
274    type SerializeMap = ser::Impossible<(), Error>;
275    type SerializeStruct = ser::Impossible<(), Error>;
276    type SerializeStructVariant = ser::Impossible<(), Error>;
277
278
279    #[inline]
280    fn serialize_bytes(self, _val: &[u8]) -> Result<Self::Ok, Self::Error> {
281        Err(<Error as ser::Error>::custom("expected tuple, received bytes"))
282    }
283
284    #[inline]
285    fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
286        Err(<Error as ser::Error>::custom("expected tuple, received bool"))
287    }
288
289    #[inline]
290    fn serialize_i8(self, _value: i8) -> Result<Self::Ok, Self::Error> {
291        Err(<Error as ser::Error>::custom("expected tuple, received i8"))
292    }
293
294    #[inline]
295    fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
296        Err(<Error as ser::Error>::custom("expected tuple, received i16"))
297    }
298
299    #[inline]
300    fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
301        Err(<Error as ser::Error>::custom("expected tuple, received i32"))
302    }
303
304    #[inline]
305    fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
306        Err(<Error as ser::Error>::custom("expected tuple, received i64"))
307    }
308
309    #[inline]
310    fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
311        Err(<Error as ser::Error>::custom("expected tuple, received u8"))
312    }
313
314    #[inline]
315    fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
316        Err(<Error as ser::Error>::custom("expected tuple, received u16"))
317    }
318
319    #[inline]
320    fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
321        Err(<Error as ser::Error>::custom("expected tuple, received u32"))
322    }
323
324    #[inline]
325    fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
326        Err(<Error as ser::Error>::custom("expected tuple, received u64"))
327    }
328
329    #[inline]
330    fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
331        Err(<Error as ser::Error>::custom("expected tuple, received f32"))
332    }
333
334    #[inline]
335    fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
336        Err(<Error as ser::Error>::custom("expected tuple, received f64"))
337    }
338
339    #[inline]
340    fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
341        Err(<Error as ser::Error>::custom("expected tuple, received char"))
342    }
343
344    #[inline]
345    fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
346        Err(<Error as ser::Error>::custom("expected tuple, received str"))
347    }
348
349    #[inline]
350    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
351        Err(<Error as ser::Error>::custom("expected tuple, received unit"))
352    }
353
354    #[inline]
355    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
356        Err(<Error as ser::Error>::custom("expected tuple, received unit_struct"))
357    }
358
359    #[inline]
360    fn serialize_unit_variant(self, _name: &'static str, _idx: u32, _variant: &'static str) -> Result<Self::Ok, Self::Error> {
361        Err(<Error as ser::Error>::custom("expected tuple, received unit_variant"))
362    }
363
364    #[inline]
365    fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
366        where T: Serialize
367    {
368        Err(<Error as ser::Error>::custom("expected tuple, received newtype_struct"))
369    }
370
371    fn serialize_newtype_variant<T: ?Sized>(self, _name: &'static str, _idx: u32, _variant: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
372        where T: Serialize
373    {
374        Err(<Error as ser::Error>::custom("expected tuple, received newtype_variant"))
375    }
376
377    #[inline]
378    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
379        Err(<Error as ser::Error>::custom("expected tuple, received none"))
380    }
381
382    #[inline]
383    fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
384        where T: Serialize
385    {
386        Err(<Error as ser::Error>::custom("expected tuple, received some"))
387    }
388
389    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
390        Err(<Error as ser::Error>::custom("expected tuple, received seq"))
391    }
392
393    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
394        // FIXME check len
395        self.fields_se = Some(ExtFieldSerializer::new());
396
397        Ok(self)
398    }
399
400    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct, Error> {
401        Err(<Error as ser::Error>::custom("expected tuple, received tuple_struct"))
402    }
403
404    fn serialize_tuple_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant, Error> {
405        Err(<Error as ser::Error>::custom("expected tuple, received tuple_variant"))
406    }
407
408    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
409        Err(<Error as ser::Error>::custom("expected tuple, received map"))
410    }
411
412    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct, Error> {
413        Err(<Error as ser::Error>::custom("expected tuple, received struct"))
414    }
415
416    fn serialize_struct_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant, Error> {
417        Err(<Error as ser::Error>::custom("expected tuple, received struct_variant"))
418    }
419}
420
421impl SerializeTuple for &mut ExtSerializer {
422    type Ok = ();
423    type Error = Error;
424
425    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
426        where T: Serialize
427    {
428        match self.fields_se {
429            Some(ref mut se) => value.serialize(&mut *se),
430            None => unreachable!()
431        }
432    }
433
434    fn end(self) -> Result<(), Error> {
435        Ok(())
436    }
437}
438
439pub struct ExtFieldSerializer {
440    tag: Option<i8>,
441    binary: Option<Vec<u8>>,
442}
443
444impl ser::Serializer for &mut ExtFieldSerializer {
445    type Ok = ();
446    type Error = Error;
447
448    type SerializeSeq = ser::Impossible<(), Error>;
449    type SerializeTuple = ser::Impossible<(), Error>;
450    type SerializeTupleStruct = ser::Impossible<(), Error>;
451    type SerializeTupleVariant = ser::Impossible<(), Error>;
452    type SerializeMap = ser::Impossible<(), Error>;
453    type SerializeStruct = ser::Impossible<(), Error>;
454    type SerializeStructVariant = ser::Impossible<(), Error>;
455
456    #[inline]
457    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
458        if self.tag.is_none() {
459            self.tag.replace(value);
460            Ok(())
461        } else {
462            Err(<Error as ser::Error>::custom("exptected i8 and bytes, received second i8"))
463        }
464    }
465
466    #[inline]
467    fn serialize_bytes(self, val: &[u8]) -> Result<Self::Ok, Self::Error> {
468        if self.binary.is_none() {
469            self.binary.replace(val.to_vec());
470
471            Ok(())
472        } else {
473            Err(<Error as ser::Error>::custom("expected i8 and bytes, received second bytes"))
474        }
475    }
476
477
478    #[inline]
479    fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
480        Err(<Error as ser::Error>::custom("expected i8 and bytes, received bool"))
481    }
482
483    #[inline]
484    fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
485        Err(<Error as ser::Error>::custom("expected i8 and bytes, received i16"))
486    }
487
488    #[inline]
489    fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
490        Err(<Error as ser::Error>::custom("expected i8 and bytes, received i32"))
491    }
492
493    #[inline]
494    fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
495        Err(<Error as ser::Error>::custom("expected i8 and bytes, received i64"))
496    }
497
498    #[inline]
499    fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
500        Err(<Error as ser::Error>::custom("expected i8 and bytes, received u8"))
501    }
502
503    #[inline]
504    fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
505        Err(<Error as ser::Error>::custom("expected i8 and bytes, received u16"))
506    }
507
508    #[inline]
509    fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
510        Err(<Error as ser::Error>::custom("expected i8 and bytes, received u32"))
511    }
512
513    #[inline]
514    fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
515        Err(<Error as ser::Error>::custom("expected i8 and bytes, received u64"))
516    }
517
518    #[inline]
519    fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
520        Err(<Error as ser::Error>::custom("expected i8 and bytes, received f32"))
521    }
522
523    #[inline]
524    fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
525        Err(<Error as ser::Error>::custom("expected i8 and bytes, received f64"))
526    }
527
528    #[inline]
529    fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
530        Err(<Error as ser::Error>::custom("expected i8 and bytes, received char"))
531    }
532
533    #[inline]
534    fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
535        Err(<Error as ser::Error>::custom("expected i8 and bytes, received str"))
536    }
537
538    #[inline]
539    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
540        Err(<Error as ser::Error>::custom("expected i8 and bytes, received unit"))
541    }
542
543    #[inline]
544    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
545        Err(<Error as ser::Error>::custom("expected i8 and bytes, received unit_struct"))
546    }
547
548    #[inline]
549    fn serialize_unit_variant(self, _name: &'static str, _idx: u32, _variant: &'static str) -> Result<Self::Ok, Self::Error> {
550        Err(<Error as ser::Error>::custom("expected i8 and bytes, received unit_variant"))
551    }
552
553    #[inline]
554    fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
555        where T: Serialize
556    {
557        Err(<Error as ser::Error>::custom("expected i8 and bytes, received newtype_struct"))
558    }
559
560    fn serialize_newtype_variant<T: ?Sized>(self, _name: &'static str, _idx: u32, _variant: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
561        where T: Serialize
562    {
563        Err(<Error as ser::Error>::custom("expected i8 and bytes, received newtype_variant"))
564    }
565
566    #[inline]
567    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
568        Err(<Error as ser::Error>::custom("expected i8 and bytes, received none"))
569    }
570
571    #[inline]
572    fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
573        where T: Serialize
574    {
575        Err(<Error as ser::Error>::custom("expected i8 and bytes, received some"))
576    }
577
578    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
579        Err(<Error as ser::Error>::custom("expected i8 and bytes, received seq"))
580    }
581
582    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
583        Err(<Error as ser::Error>::custom("expected i8 and bytes, received tuple"))
584    }
585
586    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct, Error> {
587        Err(<Error as ser::Error>::custom("expected i8 and bytes, received tuple_struct"))
588    }
589
590    fn serialize_tuple_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant, Error> {
591        Err(<Error as ser::Error>::custom("expected i8 and bytes, received tuple_variant"))
592    }
593
594    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
595        Err(<Error as ser::Error>::custom("expected i8 and bytes, received map"))
596    }
597
598    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct, Error> {
599        Err(<Error as ser::Error>::custom("expected i8 and bytes, received struct"))
600    }
601
602    fn serialize_struct_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant, Error> {
603        Err(<Error as ser::Error>::custom("expected i8 and bytes, received struct_variant"))
604    }
605}
606
607
608impl ExtSerializer {
609    fn new() -> Self {
610        Self {
611            fields_se: None
612        }
613    }
614
615    fn value(self) -> Result<Value, Error> {
616        match self.fields_se {
617            Some(fields_se) => fields_se.value(),
618            None => Err(<Error as ser::Error>::custom("expected tuple, received nothing"))
619        }
620    }
621}
622
623impl ExtFieldSerializer {
624    fn new() -> Self {
625        Self {
626            tag: None,
627            binary: None
628        }
629    }
630
631    fn value(self) -> Result<Value, Error> {
632        match (self.tag, self.binary) {
633            (Some(tag), Some(binary)) => Ok(Value::Ext(tag, binary)),
634            (Some(_), None) => Err(<Error as ser::Error>::custom("expected i8 and bytes, received i8 only")),
635            (None, Some(_)) => Err(<Error as ser::Error>::custom("expected i8 and bytes, received bytes only")),
636            (None, None) => Err(<Error as ser::Error>::custom("expected i8 and bytes, received nothing")),
637        }
638    }
639}
640
641#[doc(hidden)]
642pub struct SerializeVec {
643    vec: Vec<Value>,
644}
645
646/// Default implementation for tuple variant serialization. It packs given enums as a tuple of an
647/// index with a tuple of arguments.
648#[doc(hidden)]
649pub struct SerializeTupleVariant {
650    idx: u32,
651    vec: Vec<Value>,
652}
653
654#[doc(hidden)]
655pub struct DefaultSerializeMap {
656    map: Vec<(Value, Value)>,
657    next_key: Option<Value>,
658}
659
660#[doc(hidden)]
661pub struct SerializeStructVariant {
662    idx: u32,
663    vec: Vec<Value>,
664}
665
666impl SerializeSeq for SerializeVec {
667    type Ok = Value;
668    type Error = Error;
669
670    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
671        where T: Serialize
672    {
673        self.vec.push(to_value(&value)?);
674        Ok(())
675    }
676
677    fn end(self) -> Result<Value, Error> {
678        Ok(Value::Array(self.vec))
679    }
680}
681
682impl SerializeTuple for SerializeVec {
683    type Ok = Value;
684    type Error = Error;
685
686    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
687        where T: Serialize
688    {
689        ser::SerializeSeq::serialize_element(self, value)
690    }
691
692    fn end(self) -> Result<Value, Error> {
693        ser::SerializeSeq::end(self)
694    }
695}
696
697impl SerializeTupleStruct for SerializeVec {
698    type Ok = Value;
699    type Error = Error;
700
701    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
702        where T: Serialize
703    {
704        ser::SerializeSeq::serialize_element(self, value)
705    }
706
707    fn end(self) -> Result<Value, Error> {
708        ser::SerializeSeq::end(self)
709    }
710}
711
712impl ser::SerializeTupleVariant for SerializeTupleVariant {
713    type Ok = Value;
714    type Error = Error;
715
716    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
717        where T: Serialize
718    {
719        self.vec.push(to_value(&value)?);
720        Ok(())
721    }
722
723    fn end(self) -> Result<Value, Error> {
724        Ok(Value::Array(vec![Value::from(self.idx), Value::Array(self.vec)]))
725    }
726}
727
728impl ser::SerializeMap for DefaultSerializeMap {
729    type Ok = Value;
730    type Error = Error;
731
732    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error>
733        where T: Serialize
734    {
735        self.next_key = Some(to_value(key)?);
736        Ok(())
737    }
738
739    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
740        where T: ser::Serialize
741    {
742        // Panic because this indicates a bug in the program rather than an
743        // expected failure.
744        let key = self.next_key.take()
745            .expect("`serialize_value` called before `serialize_key`");
746        self.map.push((key, to_value(&value)?));
747        Ok(())
748    }
749
750    fn end(self) -> Result<Value, Error> {
751        Ok(Value::Map(self.map))
752    }
753}
754
755impl SerializeStruct for SerializeVec {
756    type Ok = Value;
757    type Error = Error;
758
759    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<(), Error>
760        where T: Serialize
761    {
762        ser::SerializeSeq::serialize_element(self, value)
763    }
764
765    fn end(self) -> Result<Value, Error> {
766        ser::SerializeSeq::end(self)
767    }
768}
769
770impl ser::SerializeStructVariant for SerializeStructVariant {
771    type Ok = Value;
772    type Error = Error;
773
774    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<(), Error>
775        where T: Serialize
776    {
777        self.vec.push(to_value(&value)?);
778        Ok(())
779    }
780
781    fn end(self) -> Result<Value, Error> {
782        Ok(Value::Array(vec![Value::from(self.idx), Value::Array(self.vec)]))
783    }
784}