serde_tagged/ser/adj/
struc.rs

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