Skip to main content

serde_with/
enum_map.rs

1use crate::{
2    content::ser::{Content, ContentSerializer},
3    prelude::*,
4};
5
6/// Represent a list of enum values as a map.
7///
8/// This **only works** if the enum uses the default *externally tagged* representation.
9/// Other enum representations are not supported.
10///
11/// serde data formats often represent *externally tagged* enums as maps with a single key.
12/// The key is the enum variant name, and the value is the variant value.
13/// Sometimes a map with multiple keys should be treated like a list of enum values.
14///
15/// # Examples
16///
17/// ## JSON Map with multiple keys
18///
19/// ```rust
20/// # #[cfg(feature = "macros")] {
21/// # use serde::{Deserialize, Serialize};
22/// use serde_with::{serde_as, EnumMap};
23///
24/// # #[derive(Debug, Clone, PartialEq, Eq)]
25/// #[derive(Serialize, Deserialize)]
26/// enum EnumValue {
27///     Int(i32),
28///     String(String),
29///     Unit,
30///     Tuple(i32, String, bool),
31///     Struct {
32///         a: i32,
33///         b: String,
34///         c: bool,
35///     },
36/// }
37///
38/// #[serde_as]
39/// # #[derive(Debug, Clone, PartialEq, Eq)]
40/// #[derive(Serialize, Deserialize)]
41/// struct VecEnumValues (
42///     #[serde_as(as = "EnumMap")]
43///     Vec<EnumValue>,
44/// );
45///
46/// // ---
47///
48/// // This will serialize this list of values
49/// let values = VecEnumValues(vec![
50///     EnumValue::Int(123),
51///     EnumValue::String("FooBar".to_string()),
52///     EnumValue::Int(456),
53///     EnumValue::String("XXX".to_string()),
54///     EnumValue::Unit,
55///     EnumValue::Tuple(1, "Middle".to_string(), false),
56///     EnumValue::Struct {
57///         a: 666,
58///         b: "BBB".to_string(),
59///         c: true,
60///     },
61/// ]);
62///
63/// // into this JSON map
64/// // Duplicate keys are emitted for identical enum variants.
65/// let expected =
66/// r#"{
67///   "Int": 123,
68///   "String": "FooBar",
69///   "Int": 456,
70///   "String": "XXX",
71///   "Unit": null,
72///   "Tuple": [
73///     1,
74///     "Middle",
75///     false
76///   ],
77///   "Struct": {
78///     "a": 666,
79///     "b": "BBB",
80///     "c": true
81///   }
82/// }"#;
83///
84/// // Both serialization and deserialization work flawlessly.
85/// let serialized = serde_json::to_string_pretty(&values).unwrap();
86/// assert_eq!(expected, serialized);
87/// let deserialized: VecEnumValues = serde_json::from_str(&serialized).unwrap();
88/// assert_eq!(values, deserialized);
89/// # }
90/// ```
91///
92/// ## XML structure with varying keys
93///
94/// With `serde_xml_rs` tuple and struct variants are not supported since they fail to roundtrip.
95/// The enum may have such variants as long as they are not serialized or deserialized.
96///
97/// ```
98/// # #[cfg(feature = "macros")] {
99/// # use serde::{Deserialize, Serialize};
100/// use serde_with::{serde_as, EnumMap};
101///
102/// # #[derive(Debug, Clone, PartialEq, Eq)]
103/// #[derive(Serialize, Deserialize)]
104/// enum EnumValue {
105///     Int(i32),
106///     String(String),
107///     Unit,
108/// }
109///
110/// #[serde_as]
111/// # #[derive(Debug, Clone, PartialEq, Eq)]
112/// #[derive(Serialize, Deserialize)]
113/// struct VecEnumValues {
114///     #[serde_as(as = "EnumMap")]
115///     vec: Vec<EnumValue>,
116/// }
117///
118/// // ---
119///
120/// // This will serialize this list of values
121/// let values = VecEnumValues {
122///     vec: vec![
123///         EnumValue::Int(123),
124///         EnumValue::String("FooBar".to_string()),
125///         EnumValue::Int(456),
126///         EnumValue::String("XXX".to_string()),
127///         EnumValue::Unit,
128///     ],
129/// };
130///
131/// // into this XML document
132/// // Duplicate keys are emitted for identical enum variants.
133/// let expected = r#"
134/// <?xml version="1.0" encoding="utf-8"?>
135/// <VecEnumValues>
136///     <vec>
137///         <Int>123</Int>
138///         <String>FooBar</String>
139///         <Int>456</Int>
140///         <String>XXX</String>
141///         <Unit />
142///     </vec>
143/// </VecEnumValues>"#
144/// // Remove whitespace
145/// .replace("    ", "")
146/// .replace('\n', "");
147///
148/// // Both serialization and deserialization work flawlessly.
149/// let serialized = serde_xml_rs::to_string(&values).unwrap();
150/// assert_eq!(expected, serialized);
151/// let deserialized: VecEnumValues = serde_xml_rs::from_str(&serialized).unwrap();
152/// assert_eq!(values, deserialized);
153/// # }
154/// ```
155pub struct EnumMap;
156
157impl<T> SerializeAs<Vec<T>> for EnumMap
158where
159    T: Serialize,
160{
161    fn serialize_as<S>(source: &Vec<T>, serializer: S) -> Result<S::Ok, S::Error>
162    where
163        S: Serializer,
164    {
165        source.serialize(SeqAsMapSerializer(serializer))
166    }
167}
168
169impl<'de, T> DeserializeAs<'de, Vec<T>> for EnumMap
170where
171    T: Deserialize<'de>,
172{
173    fn deserialize_as<D>(deserializer: D) -> Result<Vec<T>, D::Error>
174    where
175        D: Deserializer<'de>,
176    {
177        struct EnumMapVisitor<T> {
178            is_human_readable: bool,
179            phantom: PhantomData<T>,
180        }
181
182        impl<'de, T> Visitor<'de> for EnumMapVisitor<T>
183        where
184            T: Deserialize<'de>,
185        {
186            type Value = Vec<T>;
187
188            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
189                formatter.write_str("a map of enum values")
190            }
191
192            fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
193                Vec::deserialize(SeqDeserializer {
194                    delegate: map,
195                    is_human_readable: self.is_human_readable,
196                })
197            }
198        }
199
200        let is_human_readable = deserializer.is_human_readable();
201        deserializer.deserialize_map(EnumMapVisitor {
202            is_human_readable,
203            phantom: PhantomData,
204        })
205    }
206}
207
208static END_OF_MAP_IDENTIFIER: &str = "__PRIVATE_END_OF_MAP_MARKER__";
209
210// Serialization code below here
211
212/// Convert a sequence to a map during serialization.
213///
214/// Only `serialize_seq` is implemented and forwarded to `serialize_map` on the inner `Serializer`.
215/// The elements are serialized with [`SerializeSeqElement`].
216struct SeqAsMapSerializer<S>(S);
217
218impl<S> Serializer for SeqAsMapSerializer<S>
219where
220    S: Serializer,
221{
222    type Ok = S::Ok;
223    type Error = S::Error;
224
225    type SerializeSeq = SerializeSeqElement<S::SerializeMap>;
226    type SerializeTuple = Impossible<S::Ok, S::Error>;
227    type SerializeTupleStruct = Impossible<S::Ok, S::Error>;
228    type SerializeTupleVariant = Impossible<S::Ok, S::Error>;
229    type SerializeMap = Impossible<S::Ok, S::Error>;
230    type SerializeStruct = Impossible<S::Ok, S::Error>;
231    type SerializeStructVariant = Impossible<S::Ok, S::Error>;
232
233    fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
234        Err(SerError::custom("wrong type for EnumMap"))
235    }
236
237    fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
238        Err(SerError::custom("wrong type for EnumMap"))
239    }
240
241    fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
242        Err(SerError::custom("wrong type for EnumMap"))
243    }
244
245    fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
246        Err(SerError::custom("wrong type for EnumMap"))
247    }
248
249    fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
250        Err(SerError::custom("wrong type for EnumMap"))
251    }
252
253    fn serialize_i128(self, _v: i128) -> Result<Self::Ok, Self::Error> {
254        Err(SerError::custom("wrong type for EnumMap"))
255    }
256
257    fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
258        Err(SerError::custom("wrong type for EnumMap"))
259    }
260
261    fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
262        Err(SerError::custom("wrong type for EnumMap"))
263    }
264
265    fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
266        Err(SerError::custom("wrong type for EnumMap"))
267    }
268
269    fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
270        Err(SerError::custom("wrong type for EnumMap"))
271    }
272
273    fn serialize_u128(self, _v: u128) -> Result<Self::Ok, Self::Error> {
274        Err(SerError::custom("wrong type for EnumMap"))
275    }
276
277    fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
278        Err(SerError::custom("wrong type for EnumMap"))
279    }
280
281    fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
282        Err(SerError::custom("wrong type for EnumMap"))
283    }
284
285    fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
286        Err(SerError::custom("wrong type for EnumMap"))
287    }
288
289    fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
290        Err(SerError::custom("wrong type for EnumMap"))
291    }
292
293    fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
294        Err(SerError::custom("wrong type for EnumMap"))
295    }
296
297    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
298        Err(SerError::custom("wrong type for EnumMap"))
299    }
300
301    fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
302    where
303        T: Serialize + ?Sized,
304    {
305        Err(SerError::custom("wrong type for EnumMap"))
306    }
307
308    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
309        Err(SerError::custom("wrong type for EnumMap"))
310    }
311
312    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
313        Err(SerError::custom("wrong type for EnumMap"))
314    }
315
316    fn serialize_unit_variant(
317        self,
318        _name: &'static str,
319        _variant_index: u32,
320        _variant: &'static str,
321    ) -> Result<Self::Ok, Self::Error> {
322        Err(SerError::custom("wrong type for EnumMap"))
323    }
324
325    fn serialize_newtype_struct<T>(
326        self,
327        _name: &'static str,
328        _value: &T,
329    ) -> Result<Self::Ok, Self::Error>
330    where
331        T: Serialize + ?Sized,
332    {
333        Err(SerError::custom("wrong type for EnumMap"))
334    }
335
336    fn serialize_newtype_variant<T>(
337        self,
338        _name: &'static str,
339        _variant_index: u32,
340        _variant: &'static str,
341        _value: &T,
342    ) -> Result<Self::Ok, Self::Error>
343    where
344        T: Serialize + ?Sized,
345    {
346        Err(SerError::custom("wrong type for EnumMap"))
347    }
348
349    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
350        let is_human_readable = self.0.is_human_readable();
351        self.0
352            .serialize_map(len)
353            .map(|delegate| SerializeSeqElement {
354                delegate,
355                is_human_readable,
356            })
357    }
358
359    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
360        Err(SerError::custom("wrong type for EnumMap"))
361    }
362
363    fn serialize_tuple_struct(
364        self,
365        _name: &'static str,
366        _len: usize,
367    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
368        Err(SerError::custom("wrong type for EnumMap"))
369    }
370
371    fn serialize_tuple_variant(
372        self,
373        _name: &'static str,
374        _variant_index: u32,
375        _variant: &'static str,
376        _len: usize,
377    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
378        Err(SerError::custom("wrong type for EnumMap"))
379    }
380
381    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
382        Err(SerError::custom("wrong type for EnumMap"))
383    }
384
385    fn serialize_struct(
386        self,
387        _name: &'static str,
388        _len: usize,
389    ) -> Result<Self::SerializeStruct, Self::Error> {
390        Err(SerError::custom("wrong type for EnumMap"))
391    }
392
393    fn serialize_struct_variant(
394        self,
395        _name: &'static str,
396        _variant_index: u32,
397        _variant: &'static str,
398        _len: usize,
399    ) -> Result<Self::SerializeStructVariant, Self::Error> {
400        Err(SerError::custom("wrong type for EnumMap"))
401    }
402
403    fn is_human_readable(&self) -> bool {
404        self.0.is_human_readable()
405    }
406}
407
408/// Serialize a single element but turn the sequence into a map logic.
409///
410/// It uses [`EnumAsMapElementSerializer`] for the map element serialization.
411///
412/// The [`Serializer`] implementation handles all the `serialize_*_variant` functions and defers to [`SerializeVariant`] for the more complicated tuple and struct variants.
413struct SerializeSeqElement<M> {
414    delegate: M,
415    is_human_readable: bool,
416}
417
418impl<M> SerializeSeq for SerializeSeqElement<M>
419where
420    M: SerializeMap,
421{
422    type Ok = M::Ok;
423    type Error = M::Error;
424
425    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
426    where
427        T: Serialize + ?Sized,
428    {
429        value.serialize(EnumAsMapElementSerializer {
430            delegate: &mut self.delegate,
431            is_human_readable: self.is_human_readable,
432        })?;
433        Ok(())
434    }
435
436    fn end(self) -> Result<Self::Ok, Self::Error> {
437        self.delegate.end()
438    }
439}
440
441struct EnumAsMapElementSerializer<'a, M> {
442    delegate: &'a mut M,
443    is_human_readable: bool,
444}
445
446impl<'a, M> Serializer for EnumAsMapElementSerializer<'a, M>
447where
448    M: SerializeMap,
449{
450    type Ok = ();
451    type Error = M::Error;
452
453    type SerializeSeq = Impossible<Self::Ok, Self::Error>;
454    type SerializeTuple = Impossible<Self::Ok, Self::Error>;
455    type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
456    type SerializeTupleVariant = SerializeVariant<'a, M>;
457    type SerializeMap = Impossible<Self::Ok, Self::Error>;
458    type SerializeStruct = Impossible<Self::Ok, Self::Error>;
459    type SerializeStructVariant = SerializeVariant<'a, M>;
460
461    fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
462        Err(SerError::custom("wrong type for EnumMap"))
463    }
464
465    fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
466        Err(SerError::custom("wrong type for EnumMap"))
467    }
468
469    fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
470        Err(SerError::custom("wrong type for EnumMap"))
471    }
472
473    fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
474        Err(SerError::custom("wrong type for EnumMap"))
475    }
476
477    fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
478        Err(SerError::custom("wrong type for EnumMap"))
479    }
480
481    fn serialize_i128(self, _v: i128) -> Result<Self::Ok, Self::Error> {
482        Err(SerError::custom("wrong type for EnumMap"))
483    }
484
485    fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
486        Err(SerError::custom("wrong type for EnumMap"))
487    }
488
489    fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
490        Err(SerError::custom("wrong type for EnumMap"))
491    }
492
493    fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
494        Err(SerError::custom("wrong type for EnumMap"))
495    }
496
497    fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
498        Err(SerError::custom("wrong type for EnumMap"))
499    }
500
501    fn serialize_u128(self, _v: u128) -> Result<Self::Ok, Self::Error> {
502        Err(SerError::custom("wrong type for EnumMap"))
503    }
504
505    fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
506        Err(SerError::custom("wrong type for EnumMap"))
507    }
508
509    fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
510        Err(SerError::custom("wrong type for EnumMap"))
511    }
512
513    fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
514        Err(SerError::custom("wrong type for EnumMap"))
515    }
516
517    fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
518        Err(SerError::custom("wrong type for EnumMap"))
519    }
520
521    fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
522        Err(SerError::custom("wrong type for EnumMap"))
523    }
524
525    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
526        Err(SerError::custom("wrong type for EnumMap"))
527    }
528
529    fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
530    where
531        T: Serialize + ?Sized,
532    {
533        Err(SerError::custom("wrong type for EnumMap"))
534    }
535
536    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
537        Err(SerError::custom("wrong type for EnumMap"))
538    }
539
540    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
541        Err(SerError::custom("wrong type for EnumMap"))
542    }
543
544    fn serialize_unit_variant(
545        self,
546        _name: &'static str,
547        _variant_index: u32,
548        variant: &'static str,
549    ) -> Result<Self::Ok, Self::Error> {
550        self.delegate.serialize_entry(variant, &())?;
551        Ok(())
552    }
553
554    fn serialize_newtype_struct<T>(
555        self,
556        _name: &'static str,
557        _value: &T,
558    ) -> Result<Self::Ok, Self::Error>
559    where
560        T: Serialize + ?Sized,
561    {
562        Err(SerError::custom("wrong type for EnumMap"))
563    }
564
565    fn serialize_newtype_variant<T>(
566        self,
567        _name: &'static str,
568        _variant_index: u32,
569        variant: &'static str,
570        value: &T,
571    ) -> Result<Self::Ok, Self::Error>
572    where
573        T: Serialize + ?Sized,
574    {
575        self.delegate.serialize_entry(variant, value)?;
576        Ok(())
577    }
578
579    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
580        Err(SerError::custom("wrong type for EnumMap"))
581    }
582
583    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
584        Err(SerError::custom("wrong type for EnumMap"))
585    }
586
587    fn serialize_tuple_struct(
588        self,
589        _name: &'static str,
590        _len: usize,
591    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
592        Err(SerError::custom("wrong type for EnumMap"))
593    }
594
595    fn serialize_tuple_variant(
596        self,
597        name: &'static str,
598        _variant_index: u32,
599        variant: &'static str,
600        len: usize,
601    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
602        Ok(SerializeVariant {
603            delegate: self.delegate,
604            is_human_readable: self.is_human_readable,
605            variant,
606            content: Content::TupleStruct(name, utils::vec_with_capacity_cautious(Some(len))),
607        })
608    }
609
610    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
611        Err(SerError::custom("wrong type for EnumMap"))
612    }
613
614    fn serialize_struct(
615        self,
616        _name: &'static str,
617        _len: usize,
618    ) -> Result<Self::SerializeStruct, Self::Error> {
619        Err(SerError::custom("wrong type for EnumMap"))
620    }
621
622    fn serialize_struct_variant(
623        self,
624        name: &'static str,
625        _variant_index: u32,
626        variant: &'static str,
627        len: usize,
628    ) -> Result<Self::SerializeStructVariant, Self::Error> {
629        Ok(SerializeVariant {
630            delegate: self.delegate,
631            is_human_readable: self.is_human_readable,
632            variant,
633            content: Content::Struct(name, utils::vec_with_capacity_cautious(Some(len))),
634        })
635    }
636
637    fn is_human_readable(&self) -> bool {
638        self.is_human_readable
639    }
640}
641
642/// Serialize a struct or tuple variant enum as a map element
643///
644/// [`SerializeStructVariant`] serializes a struct variant, and [`SerializeTupleVariant`] a tuple variant.
645struct SerializeVariant<'a, M> {
646    delegate: &'a mut M,
647    is_human_readable: bool,
648    variant: &'static str,
649    content: Content,
650}
651
652impl<M> SerializeStructVariant for SerializeVariant<'_, M>
653where
654    M: SerializeMap,
655{
656    type Ok = ();
657
658    type Error = M::Error;
659
660    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
661    where
662        T: Serialize + ?Sized,
663    {
664        // Serialize to a Content type first
665        let value: Content = value.serialize(ContentSerializer::new(self.is_human_readable))?;
666        if let Content::Struct(_name, fields) = &mut self.content {
667            fields.push((key, value));
668        }
669        Ok(())
670    }
671
672    fn end(self) -> Result<Self::Ok, Self::Error> {
673        self.delegate.serialize_entry(&self.variant, &self.content)
674    }
675}
676
677impl<M> SerializeTupleVariant for SerializeVariant<'_, M>
678where
679    M: SerializeMap,
680{
681    type Ok = ();
682
683    type Error = M::Error;
684
685    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
686    where
687        T: Serialize + ?Sized,
688    {
689        // Serialize to a Content type first
690        let value: Content = value.serialize(ContentSerializer::new(self.is_human_readable))?;
691        if let Content::TupleStruct(_name, fields) = &mut self.content {
692            fields.push(value);
693        }
694        Ok(())
695    }
696
697    fn end(self) -> Result<Self::Ok, Self::Error> {
698        self.delegate.serialize_entry(&self.variant, &self.content)
699    }
700}
701
702// Below is deserialization code
703
704/// Deserialize the sequence of enum instances.
705///
706/// The main [`Deserializer`] implementation handles the outer sequence (e.g., `Vec`), while the [`SeqAccess`] implementation is responsible for the inner elements.
707struct SeqDeserializer<M> {
708    delegate: M,
709    is_human_readable: bool,
710}
711
712impl<'de, M> Deserializer<'de> for SeqDeserializer<M>
713where
714    M: MapAccess<'de>,
715{
716    type Error = M::Error;
717
718    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
719    where
720        V: Visitor<'de>,
721    {
722        self.deserialize_seq(visitor)
723    }
724
725    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
726    where
727        V: Visitor<'de>,
728    {
729        visitor.visit_seq(self)
730    }
731
732    fn is_human_readable(&self) -> bool {
733        self.is_human_readable
734    }
735
736    forward_to_deserialize_any! {
737        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
738        bytes byte_buf option unit unit_struct newtype_struct tuple
739        tuple_struct map struct enum identifier ignored_any
740    }
741}
742
743impl<'de, M> SeqAccess<'de> for SeqDeserializer<M>
744where
745    M: MapAccess<'de>,
746{
747    type Error = M::Error;
748
749    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
750    where
751        T: DeserializeSeed<'de>,
752    {
753        // We need to check if the map is done, or if there are still remaining elements.
754        // But we cannot ask the MapAccess directly.
755        // The only way is trying to deserialize, but we don't know the type yet.
756        // So we assume there is a value and try to deserialize it.
757        // If we later on find out that there is no value, we return a special error value, which we turn into `None`.
758        match seed.deserialize(EnumDeserializer {
759            delegate: &mut self.delegate,
760            is_human_readable: self.is_human_readable,
761        }) {
762            Ok(value) => Ok(Some(value)),
763            Err(err) => {
764                // Unfortunately we loose the optional aspect of MapAccess, so we need to special case an error value to mark the end of the map.
765                if err.to_string().contains(END_OF_MAP_IDENTIFIER) {
766                    Ok(None)
767                } else {
768                    Err(err)
769                }
770            }
771        }
772    }
773
774    fn size_hint(&self) -> Option<usize> {
775        self.delegate.size_hint()
776    }
777}
778
779/// Deserialize an enum from a map element
780///
781/// The [`Deserializer`] implementation is the starting point, which first calls the [`EnumAccess`] methods.
782/// The [`EnumAccess`] is used to deserialize the enum variant type of the enum.
783/// The [`VariantAccess`] is used to deserialize the value part of the enum.
784struct EnumDeserializer<M> {
785    delegate: M,
786    is_human_readable: bool,
787}
788
789impl<'de, M> Deserializer<'de> for EnumDeserializer<M>
790where
791    M: MapAccess<'de>,
792{
793    type Error = M::Error;
794
795    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
796    where
797        V: Visitor<'de>,
798    {
799        self.deserialize_enum("", &[], visitor)
800    }
801
802    fn deserialize_enum<V>(
803        self,
804        _name: &'static str,
805        _variants: &'static [&'static str],
806        visitor: V,
807    ) -> Result<V::Value, Self::Error>
808    where
809        V: Visitor<'de>,
810    {
811        visitor.visit_enum(self)
812    }
813
814    fn is_human_readable(&self) -> bool {
815        self.is_human_readable
816    }
817
818    forward_to_deserialize_any! {
819        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
820        bytes byte_buf option unit unit_struct newtype_struct seq tuple
821        tuple_struct map struct identifier ignored_any
822    }
823}
824
825impl<'de, M> EnumAccess<'de> for EnumDeserializer<M>
826where
827    M: MapAccess<'de>,
828{
829    type Error = M::Error;
830    type Variant = Self;
831
832    fn variant_seed<T>(mut self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
833    where
834        T: DeserializeSeed<'de>,
835    {
836        match self.delegate.next_key_seed(seed)? {
837            Some(key) => Ok((key, self)),
838
839            // Unfortunately we loose the optional aspect of MapAccess, so we need to special case an error value to mark the end of the map.
840            None => Err(DeError::custom(END_OF_MAP_IDENTIFIER)),
841        }
842    }
843}
844
845impl<'de, M> VariantAccess<'de> for EnumDeserializer<M>
846where
847    M: MapAccess<'de>,
848{
849    type Error = M::Error;
850
851    fn unit_variant(mut self) -> Result<(), Self::Error> {
852        self.delegate.next_value()
853    }
854
855    fn newtype_variant_seed<T>(mut self, seed: T) -> Result<T::Value, Self::Error>
856    where
857        T: DeserializeSeed<'de>,
858    {
859        self.delegate.next_value_seed(seed)
860    }
861
862    fn tuple_variant<V>(mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
863    where
864        V: Visitor<'de>,
865    {
866        self.delegate
867            .next_value_seed(SeedTupleVariant { len, visitor })
868    }
869
870    fn struct_variant<V>(
871        mut self,
872        _fields: &'static [&'static str],
873        visitor: V,
874    ) -> Result<V::Value, Self::Error>
875    where
876        V: Visitor<'de>,
877    {
878        self.delegate.next_value_seed(SeedStructVariant { visitor })
879    }
880}
881
882struct SeedTupleVariant<V> {
883    len: usize,
884    visitor: V,
885}
886
887impl<'de, V> DeserializeSeed<'de> for SeedTupleVariant<V>
888where
889    V: Visitor<'de>,
890{
891    type Value = V::Value;
892
893    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
894    where
895        D: Deserializer<'de>,
896    {
897        deserializer.deserialize_tuple(self.len, self.visitor)
898    }
899}
900
901struct SeedStructVariant<V> {
902    visitor: V,
903}
904
905impl<'de, V> DeserializeSeed<'de> for SeedStructVariant<V>
906where
907    V: Visitor<'de>,
908{
909    type Value = V::Value;
910
911    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
912    where
913        D: Deserializer<'de>,
914    {
915        deserializer.deserialize_map(self.visitor)
916    }
917}