serde_tagged/ser/adj/
map.rs

1//! Serialization of adjacently tagged values using maps.
2//!
3//! Tagging a value adjacently using this strategy will create a map with two
4//! entries, one entry contains a mapping from the tag-key to the tag and the
5//! other entry contains a mapping from the value-key to the value.
6//!
7//! # Warning
8//!
9//! If the deserialization-process depends on the tag (i.e. with
10//! [`deserialize`](::de::adj::map::deserialize) and/or
11//! [`Visitor`](::de::adj::map::Visitor)), deserialization of map-based
12//! adjacently tagged values is only supported for self-describing formats.
13//!
14//! # Examples serializing to JSON
15//!
16//! Serializing a value
17//!
18//! ```
19//! # extern crate serde_json;
20//! # extern crate serde_tagged;
21//! #
22//! # fn main() {
23//! let foo: i32 = 42;
24//!
25//! let mut serializer = serde_json::Serializer::new(std::io::stdout());
26//! serde_tagged::ser::adj::map::serialize(&mut serializer, "t", "bar", "c", &foo).unwrap();
27//! # }
28//! ```
29//!
30//! with a tag-key of `"t"`, a tag value of `"bar"`, and a value-key of `"c"` will produce
31//!
32//! ```json
33//! {
34//!     "t": "bar",
35//!     "c": 42
36//! }
37//! ```
38//!
39//! ## A Simple struct
40//!
41//! Serializing a value `foo` with
42//!
43//! ```
44//! # #[macro_use]
45//! # extern crate serde_derive;
46//! # extern crate serde_json;
47//! # extern crate serde_tagged;
48//! #
49//! #[derive(Serialize)]
50//! struct Foo {
51//!     bar: &'static str,
52//! }
53//!
54//! # fn main() {
55//! let foo = Foo { bar: "baz" };
56//!
57//! let mut serializer = serde_json::Serializer::new(std::io::stdout());
58//! serde_tagged::ser::adj::map::serialize(&mut serializer, "t", "my-tag", "c", &foo).unwrap();
59//! # }
60//! ```
61//!
62//! with a tag-key of `"t"`, a tag value of `"my-tag"`, and a value-key of `"c"` will produce
63//!
64//! ```json
65//! {
66//!     "t": "my-tag",
67//!     "c": { "bar": "baz" }
68//! }
69//! ```
70//!
71
72use std::fmt::Display;
73
74use serde;
75
76use ser::HasDelegate;
77use util::ser::content::{Content, ContentSerializer};
78use util::ser::forward;
79
80
81/// Serializes the specified tag-key, tag, value-key and value as map.
82///
83/// The specified parameters will be serialized as map with two entries, where
84/// one entry contains a mapping from the tag-key to the tag and the second
85/// entry contains a mapping from the value-key to the value. The specified
86/// serializer performs the actual serialization and thus controls the data
87/// format. For more information on this tag-format, see the
88/// [module documentation](::ser::adj::map).
89///
90/// # Note
91///
92/// You should prefer this method to the [`Serializer`](Serializer).
93pub fn serialize<S, Tk, Tv, Vk, V>(
94    serializer: S,
95    tag_key: &Tk,
96    tag_value: &Tv,
97    value_key: &Vk,
98    value: &V,
99) -> Result<S::Ok, S::Error>
100where
101    S: serde::Serializer,
102    Tk: serde::Serialize + ?Sized,
103    Tv: serde::Serialize + ?Sized,
104    Vk: serde::Serialize + ?Sized,
105    V: serde::Serialize + ?Sized,
106{
107    use serde::Serialize;
108
109    let tagged = Tagged {
110        tag_key,
111        tag_value,
112        value_key,
113        value,
114    };
115    tagged.serialize(serializer)
116}
117
118struct Tagged<'a, Tk: ?Sized + 'a, Tv: ?Sized + 'a, Vk: ?Sized + 'a, V: ?Sized + 'a> {
119    tag_key:   &'a Tk,
120    tag_value: &'a Tv,
121    value_key: &'a Vk,
122    value:     &'a V,
123}
124
125impl<'a, Tk, Tv, Vk, V> serde::Serialize for Tagged<'a, Tk, Tv, Vk, V>
126where
127    Tk: serde::Serialize + ?Sized,
128    Tv: serde::Serialize + ?Sized,
129    Vk: serde::Serialize + ?Sized,
130    V: serde::Serialize + ?Sized,
131{
132    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
133    where
134        S: serde::Serializer,
135    {
136        use serde::ser::SerializeMap;
137
138        let mut state = serializer.serialize_map(Some(2))?;
139        state.serialize_entry(self.tag_key, self.tag_value)?;
140        state.serialize_entry(self.value_key, self.value)?;
141        state.end()
142    }
143}
144
145
146/// A serializer that Serializes the specified tag-key, tag, value-key and value
147/// as map.
148///
149/// The specified parameters will be serialized as map with two entries, where
150/// one entry contains a mapping from the tag-key to the tag and the second
151/// entry contains a mapping from the value-key to the value. The specified
152/// serializer performs the actual serialization and thus controls the data
153/// format. For more information on this tag-format, see the
154/// [module documentation](::ser::adj::map).
155///
156/// # Warning
157///
158/// You should prefer the [`serialize`](serialize) function over this serializer
159/// implementation. To serialize map-entries, the serializer implementation may
160/// need to allocate memory on the heap. This can be avoided in the
161/// [`serialize`](serialize) function.
162pub struct Serializer<'a, S, Tk: ?Sized + 'a, Tv: ?Sized + 'a, Vk: ?Sized + 'a> {
163    delegate:  S,
164    tag_key:   &'a Tk,
165    tag_value: &'a Tv,
166    value_key: &'a Vk,
167}
168
169impl<'a, S, Tk, Tv, Vk> Serializer<'a, S, Tk, Tv, Vk>
170where
171    S: serde::Serializer,
172    Tk: serde::Serialize + ?Sized,
173    Tv: serde::Serialize + ?Sized,
174    Vk: serde::Serialize + ?Sized,
175{
176    /// Creates a new Serializer with the specified tag-key, tag-value,
177    /// value-key, and underlying serializer.
178    pub fn new(delegate: S, tag_key: &'a Tk, tag_value: &'a Tv, value_key: &'a Vk) -> Self {
179        Serializer {
180            delegate,
181            tag_key,
182            tag_value,
183            value_key,
184        }
185    }
186
187    fn serialize_as_map_value<V: ?Sized>(self, value: &V) -> Result<S::Ok, S::Error>
188    where
189        V: serde::Serialize,
190    {
191        use serde::ser::SerializeMap;
192
193        let mut state = self.delegate.serialize_map(Some(2))?;
194        state.serialize_entry(self.tag_key, self.tag_value)?;
195        state.serialize_entry(self.value_key, value)?;
196        state.end()
197    }
198}
199
200impl<'a, S, Tk, Tv, Vk> HasDelegate for Serializer<'a, S, Tk, Tv, Vk>
201where
202    S: serde::Serializer,
203    Tk: serde::Serialize + ?Sized,
204    Tv: serde::Serialize + ?Sized,
205    Vk: serde::Serialize + ?Sized,
206{
207    type Ok = S::Ok;
208    type Error = S::Error;
209    type Delegate = S;
210
211    fn delegate(self) -> S {
212        self.delegate
213    }
214}
215
216impl<'a, S, Tk, Tv, Vk> serde::Serializer for Serializer<'a, S, Tk, Tv, Vk>
217where
218    S: serde::Serializer,
219    Tk: serde::Serialize + ?Sized,
220    Tv: serde::Serialize + ?Sized,
221    Vk: serde::Serialize + ?Sized,
222{
223    type Ok = S::Ok;
224    type Error = S::Error;
225
226    type SerializeSeq = SerializeSeqAsMapValue<S::SerializeMap>;
227    type SerializeTuple = SerializeTupleAsMapValue<S::SerializeMap>;
228    type SerializeTupleStruct = SerializeTupleStructAsMapValue<S::SerializeMap>;
229    type SerializeMap = SerializeMapAsMapValue<S::SerializeMap>;
230    type SerializeStruct = SerializeStructAsMapValue<S::SerializeMap>;
231    type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>;
232    type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>;
233
234    fn serialize_bool(self, value: bool) -> Result<Self::Ok, Self::Error> {
235        self.serialize_as_map_value(&value)
236    }
237
238    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
239        self.serialize_as_map_value(&value)
240    }
241
242    fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> {
243        self.serialize_as_map_value(&value)
244    }
245
246    fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> {
247        self.serialize_as_map_value(&value)
248    }
249
250    fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> {
251        self.serialize_as_map_value(&value)
252    }
253
254    fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> {
255        self.serialize_as_map_value(&value)
256    }
257
258    fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> {
259        self.serialize_as_map_value(&value)
260    }
261
262    fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> {
263        self.serialize_as_map_value(&value)
264    }
265
266    fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> {
267        self.serialize_as_map_value(&value)
268    }
269
270    fn serialize_f32(self, value: f32) -> Result<Self::Ok, Self::Error> {
271        self.serialize_as_map_value(&value)
272    }
273
274    fn serialize_f64(self, value: f64) -> Result<Self::Ok, Self::Error> {
275        self.serialize_as_map_value(&value)
276    }
277
278    fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> {
279        self.serialize_as_map_value(&value)
280    }
281
282    fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
283        self.serialize_as_map_value(value)
284    }
285
286    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
287        self.serialize_as_map_value(&forward::Bytes(value))
288    }
289
290    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
291        self.serialize_as_map_value(&forward::None)
292    }
293
294    fn serialize_some<V: ?Sized>(self, value: &V) -> Result<Self::Ok, Self::Error>
295    where
296        V: serde::Serialize,
297    {
298        self.serialize_as_map_value(&forward::Some(value))
299    }
300
301    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
302        self.serialize_as_map_value(&forward::Unit)
303    }
304
305    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
306        self.serialize_as_map_value(&forward::UnitStruct(name))
307    }
308
309    fn serialize_unit_variant(
310        self,
311        name: &'static str,
312        variant_index: u32,
313        variant: &'static str,
314    ) -> Result<Self::Ok, Self::Error> {
315        self.serialize_as_map_value(&forward::UnitVariant(name, variant_index, variant))
316    }
317
318    fn serialize_newtype_struct<V: ?Sized>(
319        self,
320        name: &'static str,
321        value: &V,
322    ) -> Result<Self::Ok, Self::Error>
323    where
324        V: serde::Serialize,
325    {
326        self.serialize_as_map_value(&forward::NewtypeStruct(name, value))
327    }
328
329    fn serialize_newtype_variant<V: ?Sized>(
330        self,
331        name: &'static str,
332        variant_index: u32,
333        variant: &'static str,
334        value: &V,
335    ) -> Result<Self::Ok, Self::Error>
336    where
337        V: serde::Serialize,
338    {
339        self.serialize_as_map_value(&forward::NewtypeVariant(
340            name,
341            variant_index,
342            variant,
343            value,
344        ))
345    }
346
347    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
348        use serde::ser::SerializeMap;
349
350        let mut state = self.delegate.serialize_map(Some(1))?;
351        state.serialize_entry(self.tag_key, self.tag_value)?;
352        state.serialize_key(self.value_key)?;
353
354        Ok(SerializeSeqAsMapValue::new(state, len))
355    }
356
357    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
358        use serde::ser::SerializeMap;
359
360        let mut state = self.delegate.serialize_map(Some(1))?;
361        state.serialize_entry(self.tag_key, self.tag_value)?;
362        state.serialize_key(self.value_key)?;
363
364        Ok(SerializeTupleAsMapValue::new(state, len))
365    }
366
367    fn serialize_tuple_struct(
368        self,
369        name: &'static str,
370        len: usize,
371    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
372        use serde::ser::SerializeMap;
373
374        let mut state = self.delegate.serialize_map(Some(1))?;
375        state.serialize_entry(self.tag_key, self.tag_value)?;
376        state.serialize_key(self.value_key)?;
377
378        Ok(SerializeTupleStructAsMapValue::new(state, name, len))
379    }
380
381    fn serialize_tuple_variant(
382        self,
383        name: &'static str,
384        variant_index: u32,
385        variant: &'static str,
386        len: usize,
387    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
388        use serde::ser::SerializeMap;
389
390        let mut state = self.delegate.serialize_map(Some(1))?;
391        state.serialize_entry(self.tag_key, self.tag_value)?;
392        state.serialize_key(self.value_key)?;
393
394        Ok(SerializeTupleVariantAsMapValue::new(
395            state,
396            name,
397            variant_index,
398            variant,
399            len,
400        ))
401    }
402
403    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
404        use serde::ser::SerializeMap;
405
406        let mut state = self.delegate.serialize_map(Some(1))?;
407        state.serialize_entry(self.tag_key, self.tag_value)?;
408        state.serialize_key(self.value_key)?;
409
410        Ok(SerializeMapAsMapValue::new(state, len))
411    }
412
413    fn serialize_struct(
414        self,
415        name: &'static str,
416        len: usize,
417    ) -> Result<Self::SerializeStruct, Self::Error> {
418        use serde::ser::SerializeMap;
419
420        let mut state = self.delegate.serialize_map(Some(1))?;
421        state.serialize_entry(self.tag_key, self.tag_value)?;
422        state.serialize_key(self.value_key)?;
423
424        Ok(SerializeStructAsMapValue::new(state, name, len))
425    }
426
427    fn serialize_struct_variant(
428        self,
429        name: &'static str,
430        variant_index: u32,
431        variant: &'static str,
432        len: usize,
433    ) -> Result<Self::SerializeStructVariant, Self::Error> {
434        use serde::ser::SerializeMap;
435
436        let mut state = self.delegate.serialize_map(Some(1))?;
437        state.serialize_entry(self.tag_key, self.tag_value)?;
438        state.serialize_key(self.value_key)?;
439
440        Ok(SerializeStructVariantAsMapValue::new(
441            state,
442            name,
443            variant_index,
444            variant,
445            len,
446        ))
447    }
448
449    fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
450    where
451        I: IntoIterator,
452        <I as IntoIterator>::Item: serde::Serialize,
453    {
454        self.serialize_as_map_value(&forward::CollectSeq::new(iter))
455    }
456
457    fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
458    where
459        K: serde::Serialize,
460        V: serde::Serialize,
461        I: IntoIterator<Item = (K, V)>,
462    {
463        self.serialize_as_map_value(&forward::CollectMap::new(iter))
464    }
465
466    fn collect_str<V: ?Sized>(self, value: &V) -> Result<Self::Ok, Self::Error>
467    where
468        V: Display,
469    {
470        self.serialize_as_map_value(&forward::CollectStr(value))
471    }
472
473    fn is_human_readable(&self) -> bool {
474        self.delegate.is_human_readable()
475    }
476}
477
478
479/// Implementation of `SerializeSeq` to capture the sequence and then serialize
480/// it as map value.
481#[doc(hidden)]
482pub struct SerializeSeqAsMapValue<S> {
483    map:      S,
484    elements: Vec<Content>,
485}
486
487impl<S> SerializeSeqAsMapValue<S> {
488    fn new(map: S, len: Option<usize>) -> Self {
489        let elements = match len {
490            Some(len) => Vec::with_capacity(len),
491            None => Vec::new(),
492        };
493
494        SerializeSeqAsMapValue { map, elements }
495    }
496}
497
498impl<S> serde::ser::SerializeSeq for SerializeSeqAsMapValue<S>
499where
500    S: serde::ser::SerializeMap,
501{
502    type Ok = S::Ok;
503    type Error = S::Error;
504
505    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
506    where
507        T: serde::ser::Serialize,
508    {
509        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
510        self.elements.push(value);
511        Ok(())
512    }
513
514    fn end(mut self) -> Result<Self::Ok, Self::Error> {
515        self.map.serialize_value(&Content::Seq(self.elements))?;
516        self.map.end()
517    }
518}
519
520
521/// Implementation of `SerializeTuple` to capture the tuple and then serialize
522/// it as map value.
523#[doc(hidden)]
524pub struct SerializeTupleAsMapValue<S> {
525    map:      S,
526    elements: Vec<Content>,
527}
528
529impl<S> SerializeTupleAsMapValue<S> {
530    fn new(map: S, len: usize) -> Self {
531        SerializeTupleAsMapValue {
532            map:      map,
533            elements: Vec::with_capacity(len),
534        }
535    }
536}
537
538impl<S> serde::ser::SerializeTuple for SerializeTupleAsMapValue<S>
539where
540    S: serde::ser::SerializeMap,
541{
542    type Ok = S::Ok;
543    type Error = S::Error;
544
545    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
546    where
547        T: serde::ser::Serialize,
548    {
549        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
550        self.elements.push(value);
551        Ok(())
552    }
553
554    fn end(mut self) -> Result<Self::Ok, Self::Error> {
555        let value = Content::Tuple(self.elements);
556        self.map.serialize_value(&value)?;
557        self.map.end()
558    }
559}
560
561
562/// Implementation of `SerializeTupleStruct` to capture the tuple-struct and
563/// then serialize it as map value.
564#[doc(hidden)]
565pub struct SerializeTupleStructAsMapValue<S> {
566    map:      S,
567    name:     &'static str,
568    elements: Vec<Content>,
569}
570
571impl<S> SerializeTupleStructAsMapValue<S> {
572    fn new(map: S, name: &'static str, len: usize) -> Self {
573        SerializeTupleStructAsMapValue {
574            map:      map,
575            name:     name,
576            elements: Vec::with_capacity(len),
577        }
578    }
579}
580
581impl<S> serde::ser::SerializeTupleStruct for SerializeTupleStructAsMapValue<S>
582where
583    S: serde::ser::SerializeMap,
584{
585    type Ok = S::Ok;
586    type Error = S::Error;
587
588    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
589    where
590        T: serde::ser::Serialize,
591    {
592        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
593        self.elements.push(value);
594        Ok(())
595    }
596
597    fn end(mut self) -> Result<Self::Ok, Self::Error> {
598        let value = Content::TupleStruct(self.name, self.elements);
599        self.map.serialize_value(&value)?;
600        self.map.end()
601    }
602}
603
604
605/// Implementation of `SerializeTupleVariant` to capture the tuple-variant and
606/// then serialize it as map value.
607#[doc(hidden)]
608pub struct SerializeTupleVariantAsMapValue<S> {
609    map:           S,
610    name:          &'static str,
611    variant_index: u32,
612    variant:       &'static str,
613    elements:      Vec<Content>,
614}
615
616impl<S> SerializeTupleVariantAsMapValue<S> {
617    fn new(
618        map: S,
619        name: &'static str,
620        variant_index: u32,
621        variant: &'static str,
622        len: usize,
623    ) -> Self {
624        SerializeTupleVariantAsMapValue {
625            map:           map,
626            name:          name,
627            variant_index: variant_index,
628            variant:       variant,
629            elements:      Vec::with_capacity(len),
630        }
631    }
632}
633
634impl<S> serde::ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<S>
635where
636    S: serde::ser::SerializeMap,
637{
638    type Ok = S::Ok;
639    type Error = S::Error;
640
641    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
642    where
643        T: serde::ser::Serialize,
644    {
645        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
646        self.elements.push(value);
647        Ok(())
648    }
649
650    fn end(mut self) -> Result<Self::Ok, Self::Error> {
651        let value =
652            Content::TupleVariant(self.name, self.variant_index, self.variant, self.elements);
653
654        self.map.serialize_value(&value)?;
655        self.map.end()
656    }
657}
658
659
660/// Implementation of `SerializeMap` to capture the map and then serialize it as
661/// map value.
662#[doc(hidden)]
663pub struct SerializeMapAsMapValue<S> {
664    map:      S,
665    elements: Vec<(Content, Content)>,
666}
667
668impl<S> SerializeMapAsMapValue<S> {
669    fn new(map: S, len: Option<usize>) -> Self {
670        let elements = match len {
671            Some(len) => Vec::with_capacity(len),
672            None => Vec::new(),
673        };
674
675        SerializeMapAsMapValue { elements, map }
676    }
677}
678
679impl<S> serde::ser::SerializeMap for SerializeMapAsMapValue<S>
680where
681    S: serde::ser::SerializeMap,
682{
683    type Ok = S::Ok;
684    type Error = S::Error;
685
686    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
687    where
688        T: serde::Serialize,
689    {
690        let key = key.serialize(ContentSerializer::<S::Error>::new())?;
691        self.elements.push((key, Content::None));
692        Ok(())
693    }
694
695    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
696    where
697        T: serde::Serialize,
698    {
699        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
700        self.elements.last_mut().unwrap().1 = value;
701        Ok(())
702    }
703
704    fn end(mut self) -> Result<Self::Ok, Self::Error> {
705        self.map.serialize_value(&Content::Map(self.elements))?;
706        self.map.end()
707    }
708}
709
710
711/// Implementation of `SerializeMap` to capture the struct and then serialize it
712/// as map value.
713#[doc(hidden)]
714pub struct SerializeStructAsMapValue<S> {
715    map:    S,
716    name:   &'static str,
717    fields: Vec<(&'static str, Content)>,
718}
719
720impl<S> SerializeStructAsMapValue<S> {
721    fn new(map: S, name: &'static str, len: usize) -> Self {
722        SerializeStructAsMapValue {
723            map:    map,
724            name:   name,
725            fields: Vec::with_capacity(len),
726        }
727    }
728}
729
730impl<S> serde::ser::SerializeStruct for SerializeStructAsMapValue<S>
731where
732    S: serde::ser::SerializeMap,
733{
734    type Ok = S::Ok;
735    type Error = S::Error;
736
737    fn serialize_field<T: ?Sized>(
738        &mut self,
739        name: &'static str,
740        value: &T,
741    ) -> Result<(), Self::Error>
742    where
743        T: serde::Serialize,
744    {
745        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
746        self.fields.push((name, value));
747        Ok(())
748    }
749
750    fn end(mut self) -> Result<Self::Ok, Self::Error> {
751        let value = Content::Struct(self.name, self.fields);
752        self.map.serialize_value(&value)?;
753        self.map.end()
754    }
755}
756
757
758/// Implementation of `SerializeMap` to capture the struct-variant and then
759/// serialize it as map value.
760#[doc(hidden)]
761pub struct SerializeStructVariantAsMapValue<S> {
762    map:           S,
763    name:          &'static str,
764    variant_index: u32,
765    variant:       &'static str,
766    fields:        Vec<(&'static str, Content)>,
767}
768
769impl<S> SerializeStructVariantAsMapValue<S> {
770    fn new(
771        map: S,
772        name: &'static str,
773        variant_index: u32,
774        variant: &'static str,
775        len: usize,
776    ) -> Self {
777        SerializeStructVariantAsMapValue {
778            map:           map,
779            name:          name,
780            variant_index: variant_index,
781            variant:       variant,
782            fields:        Vec::with_capacity(len),
783        }
784    }
785}
786
787impl<S> serde::ser::SerializeStructVariant for SerializeStructVariantAsMapValue<S>
788where
789    S: serde::ser::SerializeMap,
790{
791    type Ok = S::Ok;
792    type Error = S::Error;
793
794    fn serialize_field<T: ?Sized>(
795        &mut self,
796        name: &'static str,
797        value: &T,
798    ) -> Result<(), Self::Error>
799    where
800        T: serde::Serialize,
801    {
802        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
803        self.fields.push((name, value));
804        Ok(())
805    }
806
807    fn end(mut self) -> Result<Self::Ok, Self::Error> {
808        let value =
809            Content::StructVariant(self.name, self.variant_index, self.variant, self.fields);
810        self.map.serialize_value(&value)?;
811        self.map.end()
812    }
813}