serde_with/
rust.rs

1//! De/Serialization for Rust's builtin and std types
2
3use crate::prelude::*;
4
5/// Makes a distinction between a missing, unset, or existing value
6///
7/// Some serialization formats make a distinction between missing fields, fields with a `null`
8/// value, and existing values. One such format is JSON. By default it is not easily possible to
9/// differentiate between a missing value and a field which is `null`, as they deserialize to the
10/// same value. This helper changes it, by using an `Option<Option<T>>` to deserialize into.
11///
12/// * `None`: Represents a missing value.
13/// * `Some(None)`: Represents a `null` value.
14/// * `Some(Some(value))`: Represents an existing value.
15///
16/// Note: This cannot be made compatible to `serde_as`, since skipping of values is only available on the field level.
17/// A hypothetical `DoubleOption<T>` with a `SerializeAs` implementation would allow writing something like this.
18/// This cannot work, since there is no way to tell the `Vec` to skip the inner `DoubleOption` if it is `None`.
19///
20/// ```rust
21/// # #[cfg(any())] {
22/// # struct Foobar {
23/// #[serde_as(as = "Vec<DoubleOption<_>>")]
24/// data: Vec<Option<Option<i32>>>,
25/// # }
26/// # }
27/// ```
28///
29/// # Examples
30///
31/// ```rust
32/// # use serde::{Deserialize, Serialize};
33/// #
34/// # #[derive(Debug, PartialEq, Eq)]
35/// #[derive(Deserialize, Serialize)]
36/// struct Doc {
37///     #[serde(
38///         default,                                    // <- important for deserialization
39///         skip_serializing_if = "Option::is_none",    // <- important for serialization
40///         with = "::serde_with::rust::double_option",
41///     )]
42///     a: Option<Option<u8>>,
43/// }
44/// // Missing Value
45/// let s = r#"{}"#;
46/// assert_eq!(Doc { a: None }, serde_json::from_str(s).unwrap());
47/// assert_eq!(s, serde_json::to_string(&Doc { a: None }).unwrap());
48///
49/// // Unset Value
50/// let s = r#"{"a":null}"#;
51/// assert_eq!(Doc { a: Some(None) }, serde_json::from_str(s).unwrap());
52/// assert_eq!(s, serde_json::to_string(&Doc { a: Some(None) }).unwrap());
53///
54/// // Existing Value
55/// let s = r#"{"a":5}"#;
56/// assert_eq!(Doc { a: Some(Some(5)) }, serde_json::from_str(s).unwrap());
57/// assert_eq!(s, serde_json::to_string(&Doc { a: Some(Some(5)) }).unwrap());
58/// ```
59#[allow(clippy::option_option)]
60pub mod double_option {
61    use super::*;
62
63    /// Deserialize potentially non-existing optional value
64    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
65    where
66        T: Deserialize<'de>,
67        D: Deserializer<'de>,
68    {
69        Deserialize::deserialize(deserializer).map(Some)
70    }
71
72    /// Serialize optional value
73    pub fn serialize<S, T>(values: &Option<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
74    where
75        S: Serializer,
76        T: Serialize,
77    {
78        match values {
79            None => serializer.serialize_unit(),
80            Some(None) => serializer.serialize_none(),
81            Some(Some(v)) => serializer.serialize_some(&v),
82        }
83    }
84}
85
86/// Serialize inner value if [`Some`]`(T)`. If [`None`], serialize the unit struct `()`.
87///
88/// When used in conjunction with `skip_serializing_if = "Option::is_none"` and
89/// `default`, you can build an optional value by skipping if it is [`None`], or serializing its
90/// inner value if [`Some`]`(T)`.
91///
92/// Not all serialization formats easily support optional values.
93/// While JSON uses the [`Option`] type to represent optional values and only serializes the inner
94/// part of the [`Some`]`()`, other serialization formats, such as [RON][], choose to serialize the
95/// [`Some`] around a value.
96/// This helper helps building a truly optional value for such serializers.
97///
98/// [RON]: https://github.com/ron-rs/ron
99///
100/// # Example
101///
102/// ```rust
103/// # use serde::{Deserialize, Serialize};
104/// #
105/// # #[derive(Debug, Eq, PartialEq)]
106/// #[derive(Deserialize, Serialize)]
107/// struct Doc {
108///     mandatory: usize,
109///     #[serde(
110///         default,                                    // <- important for deserialization
111///         skip_serializing_if = "Option::is_none",    // <- important for serialization
112///         with = "::serde_with::rust::unwrap_or_skip",
113///     )]
114///     optional: Option<usize>,
115/// }
116///
117/// // Transparently add/remove Some() wrapper
118/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
119/// let s = r#"(
120///     mandatory: 1,
121///     optional: 2,
122/// )"#;
123/// let v = Doc {
124///     mandatory: 1,
125///     optional: Some(2),
126/// };
127/// assert_eq!(v, ron::de::from_str(s).unwrap());
128/// assert_eq!(s, ron::ser::to_string_pretty(&v, pretty_config).unwrap());
129///
130/// // Missing values are deserialized as `None`
131/// // while `None` values are skipped during serialization.
132/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
133/// let s = r#"(
134///     mandatory: 1,
135/// )"#;
136/// let v = Doc {
137///     mandatory: 1,
138///     optional: None,
139/// };
140/// assert_eq!(v, ron::de::from_str(s).unwrap());
141/// assert_eq!(s, ron::ser::to_string_pretty(&v, pretty_config).unwrap());
142/// ```
143pub mod unwrap_or_skip {
144    use super::*;
145
146    /// Deserialize value wrapped in Some(T)
147    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
148    where
149        D: Deserializer<'de>,
150        T: Deserialize<'de>,
151    {
152        T::deserialize(deserializer).map(Some)
153    }
154
155    /// Serialize value if Some(T), unit struct if None
156    pub fn serialize<T, S>(option: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
157    where
158        T: Serialize,
159        S: Serializer,
160    {
161        if let Some(value) = option {
162            value.serialize(serializer)
163        } else {
164            ().serialize(serializer)
165        }
166    }
167}
168
169/// Ensure no duplicate values exist in a set.
170///
171/// By default serde has a last-value-wins implementation, if duplicate values for a set exist.
172/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
173/// and it can indicate an error in the serialized data.
174///
175/// This helper returns an error if two identical values exist in a set.
176///
177/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
178///
179/// # Converting to `serde_as`
180///
181/// The same functionality can be more clearly expressed using the `serde_as` macro and [`SetPreventDuplicates`].
182/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
183///
184/// ```rust
185/// # #[cfg(any())] {
186/// #[serde_as]
187/// #[derive(Deserialize, Serialize)]
188/// struct A {
189///     #[serde_as(as = "SetPreventDuplicates<_, _>")]
190///     s: HashSet<usize>,
191/// }
192/// # }
193/// ```
194///
195/// [`HashSet`]: std::collections::HashSet
196/// [`BTreeSet`]: std::collections::HashSet
197///
198/// # Example
199///
200/// ```rust
201/// # use std::collections::HashSet;
202/// # use serde::Deserialize;
203/// #
204/// # #[derive(Debug, Eq, PartialEq)]
205/// #[derive(Deserialize)]
206/// struct Doc {
207///     #[serde(with = "::serde_with::rust::sets_duplicate_value_is_error")]
208///     set: HashSet<usize>,
209/// }
210///
211/// // Sets are serialized normally,
212/// let s = r#"{"set": [1, 2, 3, 4]}"#;
213/// let v = Doc {
214///     set: HashSet::from_iter(vec![1, 2, 3, 4]),
215/// };
216/// assert_eq!(v, serde_json::from_str(s).unwrap());
217///
218/// // but create an error if duplicate values, like the `1`, exist.
219/// let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
220/// let res: Result<Doc, _> = serde_json::from_str(s);
221/// assert!(res.is_err());
222/// ```
223#[cfg(feature = "alloc")]
224pub mod sets_duplicate_value_is_error {
225    use super::*;
226    use crate::duplicate_key_impls::PreventDuplicateInsertsSet;
227
228    /// Deserialize a set and return an error on duplicate values
229    pub fn deserialize<'de, D, T, V>(deserializer: D) -> Result<T, D::Error>
230    where
231        T: PreventDuplicateInsertsSet<V>,
232        V: Deserialize<'de>,
233        D: Deserializer<'de>,
234    {
235        struct SeqVisitor<T, V> {
236            marker: PhantomData<T>,
237            set_item_type: PhantomData<V>,
238        }
239
240        impl<'de, T, V> Visitor<'de> for SeqVisitor<T, V>
241        where
242            T: PreventDuplicateInsertsSet<V>,
243            V: Deserialize<'de>,
244        {
245            type Value = T;
246
247            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
248                formatter.write_str("a sequence")
249            }
250
251            #[inline]
252            fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
253            where
254                A: SeqAccess<'de>,
255            {
256                let mut values = Self::Value::new(access.size_hint());
257
258                while let Some(value) = access.next_element()? {
259                    if !values.insert(value) {
260                        return Err(DeError::custom("invalid entry: found duplicate value"));
261                    };
262                }
263
264                Ok(values)
265            }
266        }
267
268        let visitor = SeqVisitor {
269            marker: PhantomData,
270            set_item_type: PhantomData,
271        };
272        deserializer.deserialize_seq(visitor)
273    }
274
275    /// Serialize the set with the default serializer
276    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
277    where
278        T: Serialize,
279        S: Serializer,
280    {
281        value.serialize(serializer)
282    }
283}
284
285/// Ensure no duplicate keys exist in a map.
286///
287/// By default serde has a last-value-wins implementation, if duplicate keys for a map exist.
288/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
289/// and it can indicate an error in the serialized data.
290///
291/// This helper returns an error if two identical keys exist in a map.
292///
293/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
294///
295/// # Converting to `serde_as`
296///
297/// The same functionality can be more clearly expressed using the `serde_as` macro and [`MapPreventDuplicates`].
298/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
299///
300/// ```rust
301/// # #[cfg(any())] {
302/// #[serde_as]
303/// #[derive(Deserialize, Serialize)]
304/// struct A {
305///     #[serde_as(as = "MapPreventDuplicates<_, _>")]
306///     s: HashMap<usize, usize>,
307/// }
308/// # }
309/// ```
310///
311/// [`HashMap`]: std::collections::HashMap
312/// [`BTreeMap`]: std::collections::HashMap
313///
314/// # Example
315///
316/// ```rust
317/// # use serde::Deserialize;
318/// # use std::collections::HashMap;
319/// #
320/// # #[derive(Debug, Eq, PartialEq)]
321/// #[derive(Deserialize)]
322/// struct Doc {
323///     #[serde(with = "::serde_with::rust::maps_duplicate_key_is_error")]
324///     map: HashMap<usize, usize>,
325/// }
326///
327/// // Maps are serialized normally,
328/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
329/// let mut v = Doc {
330///     map: HashMap::new(),
331/// };
332/// v.map.insert(1, 1);
333/// v.map.insert(2, 2);
334/// v.map.insert(3, 3);
335/// assert_eq!(v, serde_json::from_str(s).unwrap());
336///
337/// // but create an error if duplicate keys, like the `1`, exist.
338/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
339/// let res: Result<Doc, _> = serde_json::from_str(s);
340/// assert!(res.is_err());
341/// ```
342#[cfg(feature = "alloc")]
343pub mod maps_duplicate_key_is_error {
344    use super::*;
345    use crate::duplicate_key_impls::PreventDuplicateInsertsMap;
346
347    /// Deserialize a map and return an error on duplicate keys
348    pub fn deserialize<'de, D, T, K, V>(deserializer: D) -> Result<T, D::Error>
349    where
350        T: PreventDuplicateInsertsMap<K, V>,
351        K: Deserialize<'de>,
352        V: Deserialize<'de>,
353        D: Deserializer<'de>,
354    {
355        struct MapVisitor<T, K, V> {
356            marker: PhantomData<T>,
357            map_key_type: PhantomData<K>,
358            map_value_type: PhantomData<V>,
359        }
360
361        impl<'de, T, K, V> Visitor<'de> for MapVisitor<T, K, V>
362        where
363            T: PreventDuplicateInsertsMap<K, V>,
364            K: Deserialize<'de>,
365            V: Deserialize<'de>,
366        {
367            type Value = T;
368
369            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
370                formatter.write_str("a map")
371            }
372
373            #[inline]
374            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
375            where
376                A: MapAccess<'de>,
377            {
378                let mut values = Self::Value::new(access.size_hint());
379
380                while let Some((key, value)) = access.next_entry()? {
381                    if !values.insert(key, value) {
382                        return Err(DeError::custom("invalid entry: found duplicate key"));
383                    };
384                }
385
386                Ok(values)
387            }
388        }
389
390        let visitor = MapVisitor {
391            marker: PhantomData,
392            map_key_type: PhantomData,
393            map_value_type: PhantomData,
394        };
395        deserializer.deserialize_map(visitor)
396    }
397
398    /// Serialize the map with the default serializer
399    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
400    where
401        T: Serialize,
402        S: Serializer,
403    {
404        value.serialize(serializer)
405    }
406}
407
408/// Ensure that the last value is taken, if duplicate values exist
409///
410/// By default serde has a first-value-wins implementation, if duplicate keys for a set exist.
411/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
412///
413/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
414///
415/// # Converting to `serde_as`
416///
417/// The same functionality can be more clearly expressed using the `serde_as` macro and [`SetLastValueWins`].
418/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
419///
420/// ```rust
421/// # #[cfg(any())] {
422/// #[serde_as]
423/// #[derive(Deserialize, Serialize)]
424/// struct A {
425///     #[serde_as(as = "SetLastValueWins<_, _>")]
426///     s: HashSet<usize>,
427/// }
428/// # }
429/// ```
430///
431/// [`HashSet`]: std::collections::HashSet
432/// [`BTreeSet`]: std::collections::HashSet
433#[cfg(feature = "alloc")]
434pub mod sets_last_value_wins {
435    use super::*;
436    use crate::duplicate_key_impls::DuplicateInsertsLastWinsSet;
437
438    /// Deserialize a set and keep the last of equal values
439    pub fn deserialize<'de, D, T, V>(deserializer: D) -> Result<T, D::Error>
440    where
441        T: DuplicateInsertsLastWinsSet<V>,
442        V: Deserialize<'de>,
443        D: Deserializer<'de>,
444    {
445        struct SeqVisitor<T, V> {
446            marker: PhantomData<T>,
447            set_item_type: PhantomData<V>,
448        }
449
450        impl<'de, T, V> Visitor<'de> for SeqVisitor<T, V>
451        where
452            T: DuplicateInsertsLastWinsSet<V>,
453            V: Deserialize<'de>,
454        {
455            type Value = T;
456
457            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
458                formatter.write_str("a sequence")
459            }
460
461            #[inline]
462            fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
463            where
464                A: SeqAccess<'de>,
465            {
466                let mut values = Self::Value::new(access.size_hint());
467
468                while let Some(value) = access.next_element()? {
469                    values.replace(value);
470                }
471
472                Ok(values)
473            }
474        }
475
476        let visitor = SeqVisitor {
477            marker: PhantomData,
478            set_item_type: PhantomData,
479        };
480        deserializer.deserialize_seq(visitor)
481    }
482
483    /// Serialize the set with the default serializer
484    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
485    where
486        T: Serialize,
487        S: Serializer,
488    {
489        value.serialize(serializer)
490    }
491}
492
493/// Ensure that the first key is taken, if duplicate keys exist
494///
495/// By default serde has a last-key-wins implementation, if duplicate keys for a map exist.
496/// Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
497///
498/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
499///
500/// [`HashMap`]: std::collections::HashMap
501/// [`BTreeMap`]: std::collections::HashMap
502///
503/// # Converting to `serde_as`
504///
505/// The same functionality can be more clearly expressed using the `serde_as` macro and [`MapFirstKeyWins`].
506/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
507///
508/// ```rust
509/// # #[cfg(any())] {
510/// #[serde_as]
511/// #[derive(Deserialize, Serialize)]
512/// struct A {
513///     #[serde_as(as = "MapFirstKeyWins<_, _>")]
514///     s: HashMap<usize, usize>,
515/// }
516/// # }
517/// ```
518///
519/// # Example
520///
521/// ```rust
522/// # use serde::Deserialize;
523/// # use std::collections::HashMap;
524/// #
525/// # #[derive(Debug, Eq, PartialEq)]
526/// #[derive(Deserialize)]
527/// struct Doc {
528///     #[serde(with = "::serde_with::rust::maps_first_key_wins")]
529///     map: HashMap<usize, usize>,
530/// }
531///
532/// // Maps are serialized normally,
533/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
534/// let mut v = Doc {
535///     map: HashMap::new(),
536/// };
537/// v.map.insert(1, 1);
538/// v.map.insert(2, 2);
539/// v.map.insert(3, 3);
540/// assert_eq!(v, serde_json::from_str(s).unwrap());
541///
542/// // but create an error if duplicate keys, like the `1`, exist.
543/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
544/// let mut v = Doc {
545///     map: HashMap::new(),
546/// };
547/// v.map.insert(1, 1);
548/// v.map.insert(2, 2);
549/// assert_eq!(v, serde_json::from_str(s).unwrap());
550/// ```
551#[cfg(feature = "alloc")]
552pub mod maps_first_key_wins {
553    use super::*;
554    use crate::duplicate_key_impls::DuplicateInsertsFirstWinsMap;
555
556    /// Deserialize a map and return an error on duplicate keys
557    pub fn deserialize<'de, D, T, K, V>(deserializer: D) -> Result<T, D::Error>
558    where
559        T: DuplicateInsertsFirstWinsMap<K, V>,
560        K: Deserialize<'de>,
561        V: Deserialize<'de>,
562        D: Deserializer<'de>,
563    {
564        struct MapVisitor<T, K, V> {
565            marker: PhantomData<T>,
566            map_key_type: PhantomData<K>,
567            map_value_type: PhantomData<V>,
568        }
569
570        impl<'de, T, K, V> Visitor<'de> for MapVisitor<T, K, V>
571        where
572            T: DuplicateInsertsFirstWinsMap<K, V>,
573            K: Deserialize<'de>,
574            V: Deserialize<'de>,
575        {
576            type Value = T;
577
578            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
579                formatter.write_str("a map")
580            }
581
582            #[inline]
583            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
584            where
585                A: MapAccess<'de>,
586            {
587                let mut values = Self::Value::new(access.size_hint());
588
589                while let Some((key, value)) = access.next_entry()? {
590                    values.insert(key, value);
591                }
592
593                Ok(values)
594            }
595        }
596
597        let visitor = MapVisitor {
598            marker: PhantomData,
599            map_key_type: PhantomData,
600            map_value_type: PhantomData,
601        };
602        deserializer.deserialize_map(visitor)
603    }
604
605    /// Serialize the map with the default serializer
606    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
607    where
608        T: Serialize,
609        S: Serializer,
610    {
611        value.serialize(serializer)
612    }
613}
614
615/// Deserialize any value, ignore it, and return the default value for the type being deserialized.
616///
617/// This function can be used in two different ways:
618///
619/// 1. It is useful for instance to create an enum with a catch-all variant that will accept any incoming data.
620/// 2. [`untagged`] enum representations do not allow the `other` annotation as the fallback enum variant.
621///    With this function you can emulate an `other` variant, which can deserialize any data carrying enum.
622///
623/// **Note:** Using this function will prevent deserializing data-less enum variants.
624/// If this is a problem depends on the data format.
625/// For example, deserializing `"Bar"` as an enum in JSON would fail, since it carries no data.
626///
627/// # Examples
628///
629/// ## Deserializing a heterogeneous collection of XML nodes
630///
631/// When [`serde-xml-rs`] deserializes an XML tag to an enum, it always maps the tag
632/// name to the enum variant name, and the tag attributes and children to the enum contents.
633/// This means that in order for an enum variant to accept any XML tag, it both has to use
634/// `#[serde(other)]` to accept any tag name, and `#[serde(deserialize_with = "deserialize_ignore_any")]`
635/// to accept any attributes and children.
636///
637/// ```rust
638/// # use serde::Deserialize;
639/// use serde_with::rust::deserialize_ignore_any;
640///
641/// # #[derive(Debug, PartialEq)]
642/// #[derive(Deserialize)]
643/// #[serde(rename_all = "lowercase")]
644/// enum Item {
645///     Foo(String),
646///     Bar(String),
647///     #[serde(other, deserialize_with = "deserialize_ignore_any")]
648///     Other,
649/// }
650///
651/// // Deserialize this XML
652/// # let items: Vec<Item> = serde_xml_rs::from_str(
653/// r"
654/// <foo>a</foo>
655/// <bar>b</bar>
656/// <foo>c</foo>
657/// <unknown>d</unknown>
658/// "
659/// # ).unwrap();
660///
661/// // into these Items
662/// # let expected =
663/// vec![
664///     Item::Foo(String::from("a")),
665///     Item::Bar(String::from("b")),
666///     Item::Foo(String::from("c")),
667///     Item::Other,
668/// ]
669/// # ;
670/// # assert_eq!(expected, items);
671/// ```
672///
673/// ## Simulating an `other` enum variant in an `untagged` enum
674///
675/// ```rust
676/// # use serde::Deserialize;
677/// # use serde_json::json;
678/// use serde_with::rust::deserialize_ignore_any;
679///
680/// # #[derive(Debug, PartialEq)]
681/// #[derive(Deserialize)]
682/// #[serde(untagged)]
683/// enum Item {
684///     Foo{x: u8},
685///     #[serde(deserialize_with = "deserialize_ignore_any")]
686///     Other,
687/// }
688///
689/// // Deserialize this JSON
690/// # let items: Vec<Item> = serde_json::from_value(
691/// json!([
692///     {"y": 1},
693///     {"x": 1},
694/// ])
695/// # ).unwrap();
696///
697/// // into these Items
698/// # let expected =
699/// vec![Item::Other, Item::Foo{x: 1}]
700/// # ;
701/// # assert_eq!(expected, items);
702/// ```
703///
704/// [`serde-xml-rs`]: https://docs.rs/serde-xml-rs
705/// [`untagged`]: https://serde.rs/enum-representations.html#untagged
706pub fn deserialize_ignore_any<'de, D: Deserializer<'de>, T: Default>(
707    deserializer: D,
708) -> Result<T, D::Error> {
709    IgnoredAny::deserialize(deserializer).map(|_| T::default())
710}