Debian Codegraph @

third_party/rust/serde_with/src/enum_map.rs

raw
1 use 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 /// ```
155 pub struct EnumMap;
156
157 impl<T> SerializeAs<Vec<T>> for EnumMap
158 where
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
169 impl<'de, T> DeserializeAs<'de, Vec<T>> for EnumMap
170 where
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
208 static 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`].
216 struct SeqAsMapSerializer<S>(S);
217
218 impl<S> Serializer for SeqAsMapSerializer<S>
219 where
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 is_human_readable(&self) -> bool {
234 self.0.is_human_readable()
235 }
236
237 fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
238 Err(SerError::custom("wrong type for EnumMap"))
239 }
240
241 fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
242 Err(SerError::custom("wrong type for EnumMap"))
243 }
244
245 fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
246 Err(SerError::custom("wrong type for EnumMap"))
247 }
248
249 fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
250 Err(SerError::custom("wrong type for EnumMap"))
251 }
252
253 fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
254 Err(SerError::custom("wrong type for EnumMap"))
255 }
256
257 fn serialize_i128(self, _v: i128) -> Result<Self::Ok, Self::Error> {
258 Err(SerError::custom("wrong type for EnumMap"))
259 }
260
261 fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
262 Err(SerError::custom("wrong type for EnumMap"))
263 }
264
265 fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
266 Err(SerError::custom("wrong type for EnumMap"))
267 }
268
269 fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
270 Err(SerError::custom("wrong type for EnumMap"))
271 }
272
273 fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
274 Err(SerError::custom("wrong type for EnumMap"))
275 }
276
277 fn serialize_u128(self, _v: u128) -> Result<Self::Ok, Self::Error> {
278 Err(SerError::custom("wrong type for EnumMap"))
279 }
280
281 fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
282 Err(SerError::custom("wrong type for EnumMap"))
283 }
284
285 fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
286 Err(SerError::custom("wrong type for EnumMap"))
287 }
288
289 fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
290 Err(SerError::custom("wrong type for EnumMap"))
291 }
292
293 fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
294 Err(SerError::custom("wrong type for EnumMap"))
295 }
296
297 fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
298 Err(SerError::custom("wrong type for EnumMap"))
299 }
300
301 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
302 Err(SerError::custom("wrong type for EnumMap"))
303 }
304
305 fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
306 where
307 T: Serialize + ?Sized,
308 {
309 Err(SerError::custom("wrong type for EnumMap"))
310 }
311
312 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
313 Err(SerError::custom("wrong type for EnumMap"))
314 }
315
316 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
317 Err(SerError::custom("wrong type for EnumMap"))
318 }
319
320 fn serialize_unit_variant(
321 self,
322 _name: &'static str,
323 _variant_index: u32,
324 _variant: &'static str,
325 ) -> Result<Self::Ok, Self::Error> {
326 Err(SerError::custom("wrong type for EnumMap"))
327 }
328
329 fn serialize_newtype_struct<T>(
330 self,
331 _name: &'static str,
332 _value: &T,
333 ) -> Result<Self::Ok, Self::Error>
334 where
335 T: Serialize + ?Sized,
336 {
337 Err(SerError::custom("wrong type for EnumMap"))
338 }
339
340 fn serialize_newtype_variant<T>(
341 self,
342 _name: &'static str,
343 _variant_index: u32,
344 _variant: &'static str,
345 _value: &T,
346 ) -> Result<Self::Ok, Self::Error>
347 where
348 T: Serialize + ?Sized,
349 {
350 Err(SerError::custom("wrong type for EnumMap"))
351 }
352
353 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
354 let is_human_readable = self.0.is_human_readable();
355 self.0
356 .serialize_map(len)
357 .map(|delegate| SerializeSeqElement {
358 delegate,
359 is_human_readable,
360 })
361 }
362
363 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
364 Err(SerError::custom("wrong type for EnumMap"))
365 }
366
367 fn serialize_tuple_struct(
368 self,
369 _name: &'static str,
370 _len: usize,
371 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
372 Err(SerError::custom("wrong type for EnumMap"))
373 }
374
375 fn serialize_tuple_variant(
376 self,
377 _name: &'static str,
378 _variant_index: u32,
379 _variant: &'static str,
380 _len: usize,
381 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
382 Err(SerError::custom("wrong type for EnumMap"))
383 }
384
385 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
386 Err(SerError::custom("wrong type for EnumMap"))
387 }
388
389 fn serialize_struct(
390 self,
391 _name: &'static str,
392 _len: usize,
393 ) -> Result<Self::SerializeStruct, Self::Error> {
394 Err(SerError::custom("wrong type for EnumMap"))
395 }
396
397 fn serialize_struct_variant(
398 self,
399 _name: &'static str,
400 _variant_index: u32,
401 _variant: &'static str,
402 _len: usize,
403 ) -> Result<Self::SerializeStructVariant, Self::Error> {
404 Err(SerError::custom("wrong type for EnumMap"))
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.
413 struct SerializeSeqElement<M> {
414 delegate: M,
415 is_human_readable: bool,
416 }
417
418 impl<M> SerializeSeq for SerializeSeqElement<M>
419 where
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
441 struct EnumAsMapElementSerializer<'a, M> {
442 delegate: &'a mut M,
443 is_human_readable: bool,
444 }
445
446 impl<'a, M> Serializer for EnumAsMapElementSerializer<'a, M>
447 where
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 is_human_readable(&self) -> bool {
462 self.is_human_readable
463 }
464
465 fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
466 Err(SerError::custom("wrong type for EnumMap"))
467 }
468
469 fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
470 Err(SerError::custom("wrong type for EnumMap"))
471 }
472
473 fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
474 Err(SerError::custom("wrong type for EnumMap"))
475 }
476
477 fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
478 Err(SerError::custom("wrong type for EnumMap"))
479 }
480
481 fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
482 Err(SerError::custom("wrong type for EnumMap"))
483 }
484
485 fn serialize_i128(self, _v: i128) -> Result<Self::Ok, Self::Error> {
486 Err(SerError::custom("wrong type for EnumMap"))
487 }
488
489 fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
490 Err(SerError::custom("wrong type for EnumMap"))
491 }
492
493 fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
494 Err(SerError::custom("wrong type for EnumMap"))
495 }
496
497 fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
498 Err(SerError::custom("wrong type for EnumMap"))
499 }
500
501 fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
502 Err(SerError::custom("wrong type for EnumMap"))
503 }
504
505 fn serialize_u128(self, _v: u128) -> Result<Self::Ok, Self::Error> {
506 Err(SerError::custom("wrong type for EnumMap"))
507 }
508
509 fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
510 Err(SerError::custom("wrong type for EnumMap"))
511 }
512
513 fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
514 Err(SerError::custom("wrong type for EnumMap"))
515 }
516
517 fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
518 Err(SerError::custom("wrong type for EnumMap"))
519 }
520
521 fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
522 Err(SerError::custom("wrong type for EnumMap"))
523 }
524
525 fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
526 Err(SerError::custom("wrong type for EnumMap"))
527 }
528
529 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
530 Err(SerError::custom("wrong type for EnumMap"))
531 }
532
533 fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
534 where
535 T: Serialize + ?Sized,
536 {
537 Err(SerError::custom("wrong type for EnumMap"))
538 }
539
540 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
541 Err(SerError::custom("wrong type for EnumMap"))
542 }
543
544 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
545 Err(SerError::custom("wrong type for EnumMap"))
546 }
547
548 fn serialize_unit_variant(
549 self,
550 _name: &'static str,
551 _variant_index: u32,
552 variant: &'static str,
553 ) -> Result<Self::Ok, Self::Error> {
554 self.delegate.serialize_entry(variant, &())?;
555 Ok(())
556 }
557
558 fn serialize_newtype_struct<T>(
559 self,
560 _name: &'static str,
561 _value: &T,
562 ) -> Result<Self::Ok, Self::Error>
563 where
564 T: Serialize + ?Sized,
565 {
566 Err(SerError::custom("wrong type for EnumMap"))
567 }
568
569 fn serialize_newtype_variant<T>(
570 self,
571 _name: &'static str,
572 _variant_index: u32,
573 variant: &'static str,
574 value: &T,
575 ) -> Result<Self::Ok, Self::Error>
576 where
577 T: Serialize + ?Sized,
578 {
579 self.delegate.serialize_entry(variant, value)?;
580 Ok(())
581 }
582
583 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
584 Err(SerError::custom("wrong type for EnumMap"))
585 }
586
587 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
588 Err(SerError::custom("wrong type for EnumMap"))
589 }
590
591 fn serialize_tuple_struct(
592 self,
593 _name: &'static str,
594 _len: usize,
595 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
596 Err(SerError::custom("wrong type for EnumMap"))
597 }
598
599 fn serialize_tuple_variant(
600 self,
601 name: &'static str,
602 _variant_index: u32,
603 variant: &'static str,
604 len: usize,
605 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
606 Ok(SerializeVariant {
607 delegate: self.delegate,
608 is_human_readable: self.is_human_readable,
609 variant,
610 content: Content::TupleStruct(name, Vec::with_capacity(len)),
611 })
612 }
613
614 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
615 Err(SerError::custom("wrong type for EnumMap"))
616 }
617
618 fn serialize_struct(
619 self,
620 _name: &'static str,
621 _len: usize,
622 ) -> Result<Self::SerializeStruct, Self::Error> {
623 Err(SerError::custom("wrong type for EnumMap"))
624 }
625
626 fn serialize_struct_variant(
627 self,
628 name: &'static str,
629 _variant_index: u32,
630 variant: &'static str,
631 len: usize,
632 ) -> Result<Self::SerializeStructVariant, Self::Error> {
633 Ok(SerializeVariant {
634 delegate: self.delegate,
635 is_human_readable: self.is_human_readable,
636 variant,
637 content: Content::Struct(name, Vec::with_capacity(len)),
638 })
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.
645 struct SerializeVariant<'a, M> {
646 delegate: &'a mut M,
647 is_human_readable: bool,
648 variant: &'static str,
649 content: Content,
650 }
651
652 impl<M> SerializeStructVariant for SerializeVariant<'_, M>
653 where
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
677 impl<M> SerializeTupleVariant for SerializeVariant<'_, M>
678 where
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.
707 struct SeqDeserializer<M> {
708 delegate: M,
709 is_human_readable: bool,
710 }
711
712 impl<'de, M> Deserializer<'de> for SeqDeserializer<M>
713 where
714 M: MapAccess<'de>,
715 {
716 type Error = M::Error;
717
718 fn is_human_readable(&self) -> bool {
719 self.is_human_readable
720 }
721
722 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
723 where
724 V: Visitor<'de>,
725 {
726 visitor.visit_seq(self)
727 }
728
729 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
730 where
731 V: Visitor<'de>,
732 {
733 self.deserialize_seq(visitor)
734 }
735
736 serde::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
743 impl<'de, M> SeqAccess<'de> for SeqDeserializer<M>
744 where
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.
784 struct EnumDeserializer<M> {
785 delegate: M,
786 is_human_readable: bool,
787 }
788
789 impl<'de, M> Deserializer<'de> for EnumDeserializer<M>
790 where
791 M: MapAccess<'de>,
792 {
793 type Error = M::Error;
794
795 fn is_human_readable(&self) -> bool {
796 self.is_human_readable
797 }
798
799 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
800 where
801 V: Visitor<'de>,
802 {
803 self.deserialize_enum("", &[], visitor)
804 }
805
806 fn deserialize_enum<V>(
807 self,
808 _name: &'static str,
809 _variants: &'static [&'static str],
810 visitor: V,
811 ) -> Result<V::Value, Self::Error>
812 where
813 V: Visitor<'de>,
814 {
815 visitor.visit_enum(self)
816 }
817
818 serde::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
825 impl<'de, M> EnumAccess<'de> for EnumDeserializer<M>
826 where
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
845 impl<'de, M> VariantAccess<'de> for EnumDeserializer<M>
846 where
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
882 struct SeedTupleVariant<V> {
883 len: usize,
884 visitor: V,
885 }
886
887 impl<'de, V> DeserializeSeed<'de> for SeedTupleVariant<V>
888 where
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
901 struct SeedStructVariant<V> {
902 visitor: V,
903 }
904
905 impl<'de, V> DeserializeSeed<'de> for SeedStructVariant<V>
906 where
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 }