serde_yaml/value/
ser.rs

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