Skip to main content

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(false)] {
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(false)] {
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::BTreeSet
197///
198/// # Example
199///
200/// ```rust
201/// # extern crate alloc;
202/// # use alloc::collections::BTreeSet;
203/// # use serde::Deserialize;
204/// #
205/// # #[derive(Debug, Eq, PartialEq)]
206/// #[derive(Deserialize)]
207/// struct Doc {
208///     #[serde(with = "::serde_with::rust::sets_duplicate_value_is_error")]
209///     set: BTreeSet<usize>,
210/// }
211///
212/// // Sets are serialized normally,
213/// let s = r#"{"set": [1, 2, 3, 4]}"#;
214/// let v = Doc {
215///     set: BTreeSet::from_iter(vec![1, 2, 3, 4]),
216/// };
217/// assert_eq!(v, serde_json::from_str(s).unwrap());
218///
219/// // but create an error if duplicate values, like the `1`, exist.
220/// let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
221/// let res: Result<Doc, _> = serde_json::from_str(s);
222/// assert!(res.is_err());
223/// ```
224#[cfg(feature = "alloc")]
225pub mod sets_duplicate_value_is_error {
226    use super::*;
227    use crate::duplicate_key_impls::PreventDuplicateInsertsSet;
228
229    /// Deserialize a set and return an error on duplicate values
230    pub fn deserialize<'de, D, T, V>(deserializer: D) -> Result<T, D::Error>
231    where
232        T: PreventDuplicateInsertsSet<V>,
233        V: Deserialize<'de>,
234        D: Deserializer<'de>,
235    {
236        struct SeqVisitor<T, V> {
237            marker: PhantomData<T>,
238            set_item_type: PhantomData<V>,
239        }
240
241        impl<'de, T, V> Visitor<'de> for SeqVisitor<T, V>
242        where
243            T: PreventDuplicateInsertsSet<V>,
244            V: Deserialize<'de>,
245        {
246            type Value = T;
247
248            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
249                formatter.write_str("a sequence")
250            }
251
252            #[inline]
253            fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
254            where
255                A: SeqAccess<'de>,
256            {
257                let mut values = Self::Value::new(access.size_hint());
258
259                while let Some(value) = access.next_element()? {
260                    if !values.insert(value) {
261                        return Err(DeError::custom("invalid entry: found duplicate value"));
262                    };
263                }
264
265                Ok(values)
266            }
267        }
268
269        let visitor = SeqVisitor {
270            marker: PhantomData,
271            set_item_type: PhantomData,
272        };
273        deserializer.deserialize_seq(visitor)
274    }
275
276    /// Serialize the set with the default serializer
277    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
278    where
279        T: Serialize,
280        S: Serializer,
281    {
282        value.serialize(serializer)
283    }
284}
285
286/// Ensure no duplicate keys exist in a map.
287///
288/// By default serde has a last-value-wins implementation, if duplicate keys for a map exist.
289/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
290/// and it can indicate an error in the serialized data.
291///
292/// This helper returns an error if two identical keys exist in a map.
293///
294/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
295///
296/// # Converting to `serde_as`
297///
298/// The same functionality can be more clearly expressed using the `serde_as` macro and [`MapPreventDuplicates`].
299/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
300///
301/// ```rust
302/// # #[cfg(false)] {
303/// #[serde_as]
304/// #[derive(Deserialize, Serialize)]
305/// struct A {
306///     #[serde_as(as = "MapPreventDuplicates<_, _>")]
307///     s: HashMap<usize, usize>,
308/// }
309/// # }
310/// ```
311///
312/// [`HashMap`]: std::collections::HashMap
313/// [`BTreeMap`]: std::collections::BTreeMap
314///
315/// # Example
316///
317/// ```rust
318/// # extern crate alloc;
319/// # use serde::Deserialize;
320/// # use alloc::collections::BTreeMap;
321/// #
322/// # #[derive(Debug, Eq, PartialEq)]
323/// #[derive(Deserialize)]
324/// struct Doc {
325///     #[serde(with = "::serde_with::rust::maps_duplicate_key_is_error")]
326///     map: BTreeMap<usize, usize>,
327/// }
328///
329/// // Maps are serialized normally,
330/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
331/// let mut v = Doc {
332///     map: BTreeMap::new(),
333/// };
334/// v.map.insert(1, 1);
335/// v.map.insert(2, 2);
336/// v.map.insert(3, 3);
337/// assert_eq!(v, serde_json::from_str(s).unwrap());
338///
339/// // but create an error if duplicate keys, like the `1`, exist.
340/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
341/// let res: Result<Doc, _> = serde_json::from_str(s);
342/// assert!(res.is_err());
343/// ```
344#[cfg(feature = "alloc")]
345pub mod maps_duplicate_key_is_error {
346    use super::*;
347    use crate::duplicate_key_impls::PreventDuplicateInsertsMap;
348
349    /// Deserialize a map and return an error on duplicate keys
350    pub fn deserialize<'de, D, T, K, V>(deserializer: D) -> Result<T, D::Error>
351    where
352        T: PreventDuplicateInsertsMap<K, V>,
353        K: Deserialize<'de>,
354        V: Deserialize<'de>,
355        D: Deserializer<'de>,
356    {
357        struct MapVisitor<T, K, V> {
358            marker: PhantomData<T>,
359            map_key_type: PhantomData<K>,
360            map_value_type: PhantomData<V>,
361        }
362
363        impl<'de, T, K, V> Visitor<'de> for MapVisitor<T, K, V>
364        where
365            T: PreventDuplicateInsertsMap<K, V>,
366            K: Deserialize<'de>,
367            V: Deserialize<'de>,
368        {
369            type Value = T;
370
371            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
372                formatter.write_str("a map")
373            }
374
375            #[inline]
376            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
377            where
378                A: MapAccess<'de>,
379            {
380                let mut values = Self::Value::new(access.size_hint());
381
382                while let Some((key, value)) = access.next_entry()? {
383                    if !values.insert(key, value) {
384                        return Err(DeError::custom("invalid entry: found duplicate key"));
385                    };
386                }
387
388                Ok(values)
389            }
390        }
391
392        let visitor = MapVisitor {
393            marker: PhantomData,
394            map_key_type: PhantomData,
395            map_value_type: PhantomData,
396        };
397        deserializer.deserialize_map(visitor)
398    }
399
400    /// Serialize the map with the default serializer
401    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
402    where
403        T: Serialize,
404        S: Serializer,
405    {
406        value.serialize(serializer)
407    }
408}
409
410/// Ensure that the last value is taken, if duplicate values exist
411///
412/// By default serde has a first-value-wins implementation, if duplicate keys for a set exist.
413/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
414///
415/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
416///
417/// # Converting to `serde_as`
418///
419/// The same functionality can be more clearly expressed using the `serde_as` macro and [`SetLastValueWins`].
420/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
421///
422/// ```rust
423/// # #[cfg(false)] {
424/// #[serde_as]
425/// #[derive(Deserialize, Serialize)]
426/// struct A {
427///     #[serde_as(as = "SetLastValueWins<_, _>")]
428///     s: HashSet<usize>,
429/// }
430/// # }
431/// ```
432///
433/// [`HashSet`]: std::collections::HashSet
434/// [`BTreeSet`]: std::collections::BTreeSet
435#[cfg(feature = "alloc")]
436pub mod sets_last_value_wins {
437    use super::*;
438    use crate::duplicate_key_impls::DuplicateInsertsLastWinsSet;
439
440    /// Deserialize a set and keep the last of equal values
441    pub fn deserialize<'de, D, T, V>(deserializer: D) -> Result<T, D::Error>
442    where
443        T: DuplicateInsertsLastWinsSet<V>,
444        V: Deserialize<'de>,
445        D: Deserializer<'de>,
446    {
447        struct SeqVisitor<T, V> {
448            marker: PhantomData<T>,
449            set_item_type: PhantomData<V>,
450        }
451
452        impl<'de, T, V> Visitor<'de> for SeqVisitor<T, V>
453        where
454            T: DuplicateInsertsLastWinsSet<V>,
455            V: Deserialize<'de>,
456        {
457            type Value = T;
458
459            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
460                formatter.write_str("a sequence")
461            }
462
463            #[inline]
464            fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
465            where
466                A: SeqAccess<'de>,
467            {
468                let mut values = Self::Value::new(access.size_hint());
469
470                while let Some(value) = access.next_element()? {
471                    values.replace(value);
472                }
473
474                Ok(values)
475            }
476        }
477
478        let visitor = SeqVisitor {
479            marker: PhantomData,
480            set_item_type: PhantomData,
481        };
482        deserializer.deserialize_seq(visitor)
483    }
484
485    /// Serialize the set with the default serializer
486    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
487    where
488        T: Serialize,
489        S: Serializer,
490    {
491        value.serialize(serializer)
492    }
493}
494
495/// Ensure that the first key is taken, if duplicate keys exist
496///
497/// By default serde has a last-key-wins implementation, if duplicate keys for a map exist.
498/// Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
499///
500/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
501///
502/// [`HashMap`]: std::collections::HashMap
503/// [`BTreeMap`]: std::collections::BTreeMap
504///
505/// # Converting to `serde_as`
506///
507/// The same functionality can be more clearly expressed using the `serde_as` macro and [`MapFirstKeyWins`].
508/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
509///
510/// ```rust
511/// # #[cfg(false)] {
512/// #[serde_as]
513/// #[derive(Deserialize, Serialize)]
514/// struct A {
515///     #[serde_as(as = "MapFirstKeyWins<_, _>")]
516///     s: HashMap<usize, usize>,
517/// }
518/// # }
519/// ```
520///
521/// # Example
522///
523/// ```rust
524/// # extern crate alloc;
525/// # use serde::Deserialize;
526/// # use alloc::collections::BTreeMap;
527/// #
528/// # #[derive(Debug, Eq, PartialEq)]
529/// #[derive(Deserialize)]
530/// struct Doc {
531///     #[serde(with = "::serde_with::rust::maps_first_key_wins")]
532///     map: BTreeMap<usize, usize>,
533/// }
534///
535/// // Maps are serialized normally,
536/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
537/// let mut v = Doc {
538///     map: BTreeMap::new(),
539/// };
540/// v.map.insert(1, 1);
541/// v.map.insert(2, 2);
542/// v.map.insert(3, 3);
543/// assert_eq!(v, serde_json::from_str(s).unwrap());
544///
545/// // but create an error if duplicate keys, like the `1`, exist.
546/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
547/// let mut v = Doc {
548///     map: BTreeMap::new(),
549/// };
550/// v.map.insert(1, 1);
551/// v.map.insert(2, 2);
552/// assert_eq!(v, serde_json::from_str(s).unwrap());
553/// ```
554#[cfg(feature = "alloc")]
555pub mod maps_first_key_wins {
556    use super::*;
557    use crate::duplicate_key_impls::DuplicateInsertsFirstWinsMap;
558
559    /// Deserialize a map and return an error on duplicate keys
560    pub fn deserialize<'de, D, T, K, V>(deserializer: D) -> Result<T, D::Error>
561    where
562        T: DuplicateInsertsFirstWinsMap<K, V>,
563        K: Deserialize<'de>,
564        V: Deserialize<'de>,
565        D: Deserializer<'de>,
566    {
567        struct MapVisitor<T, K, V> {
568            marker: PhantomData<T>,
569            map_key_type: PhantomData<K>,
570            map_value_type: PhantomData<V>,
571        }
572
573        impl<'de, T, K, V> Visitor<'de> for MapVisitor<T, K, V>
574        where
575            T: DuplicateInsertsFirstWinsMap<K, V>,
576            K: Deserialize<'de>,
577            V: Deserialize<'de>,
578        {
579            type Value = T;
580
581            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
582                formatter.write_str("a map")
583            }
584
585            #[inline]
586            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
587            where
588                A: MapAccess<'de>,
589            {
590                let mut values = Self::Value::new(access.size_hint());
591
592                while let Some((key, value)) = access.next_entry()? {
593                    values.insert(key, value);
594                }
595
596                Ok(values)
597            }
598        }
599
600        let visitor = MapVisitor {
601            marker: PhantomData,
602            map_key_type: PhantomData,
603            map_value_type: PhantomData,
604        };
605        deserializer.deserialize_map(visitor)
606    }
607
608    /// Serialize the map with the default serializer
609    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
610    where
611        T: Serialize,
612        S: Serializer,
613    {
614        value.serialize(serializer)
615    }
616}
617
618/// Deserialize any value, ignore it, and return the default value for the type being deserialized.
619///
620/// This function can be used in two different ways:
621///
622/// 1. It is useful for instance to create an enum with a catch-all variant that will accept any incoming data.
623/// 2. [`untagged`] enum representations do not allow the `other` annotation as the fallback enum variant.
624///    With this function you can emulate an `other` variant, which can deserialize any data carrying enum.
625///
626/// **Note:** Using this function will prevent deserializing data-less enum variants.
627/// If this is a problem depends on the data format.
628/// For example, deserializing `"Bar"` as an enum in JSON would fail, since it carries no data.
629///
630/// # Examples
631///
632/// ## Deserializing a heterogeneous collection of XML nodes
633///
634/// When [`serde-xml-rs`] deserializes an XML tag to an enum, it always maps the tag
635/// name to the enum variant name, and the tag attributes and children to the enum contents.
636/// This means that in order for an enum variant to accept any XML tag, it both has to use
637/// `#[serde(other)]` to accept any tag name, and `#[serde(deserialize_with = "deserialize_ignore_any")]`
638/// to accept any attributes and children.
639///
640/// ```rust
641/// # use serde::Deserialize;
642/// use serde_with::rust::deserialize_ignore_any;
643///
644/// # #[derive(Debug, PartialEq)]
645/// #[derive(Deserialize)]
646/// struct Root {
647///     values: Vec<Item>,
648/// }
649///
650/// # #[derive(Debug, PartialEq)]
651/// #[derive(Deserialize)]
652/// #[serde(rename_all = "lowercase")]
653/// enum Item {
654///     Foo(String),
655///     Bar(String),
656///     #[serde(other, deserialize_with = "deserialize_ignore_any")]
657///     Other,
658/// }
659///
660/// // Deserialize this XML
661/// # let items: Root = serde_xml_rs::from_str(
662/// r#"<?xml version="1.0" encoding="UTF-8"?>
663/// <Root>
664///     <values>
665///         <foo>a</foo>
666///     </values>
667///     <values>
668///         <bar>b</bar>
669///     </values>
670///     <values>
671///         <foo>c</foo>
672///     </values>
673///     <values>
674///         <unknown>d</unknown>
675///     </values>
676/// </Root>"#
677/// # ).unwrap();
678///
679/// // into these Items
680/// # let expected =
681/// Root {
682///     values: vec![
683///         Item::Foo(String::from("a")),
684///         Item::Bar(String::from("b")),
685///         Item::Foo(String::from("c")),
686///         Item::Other,
687///     ]
688/// }
689/// # ;
690/// # assert_eq!(expected, items);
691/// ```
692///
693/// ## Simulating an `other` enum variant in an `untagged` enum
694///
695/// ```rust
696/// # use serde::Deserialize;
697/// # use serde_json::json;
698/// use serde_with::rust::deserialize_ignore_any;
699///
700/// # #[derive(Debug, PartialEq)]
701/// #[derive(Deserialize)]
702/// #[serde(untagged)]
703/// enum Item {
704///     Foo{x: u8},
705///     #[serde(deserialize_with = "deserialize_ignore_any")]
706///     Other,
707/// }
708///
709/// // Deserialize this JSON
710/// # let items: Vec<Item> = serde_json::from_value(
711/// json!([
712///     {"y": 1},
713///     {"x": 1},
714/// ])
715/// # ).unwrap();
716///
717/// // into these Items
718/// # let expected =
719/// vec![Item::Other, Item::Foo{x: 1}]
720/// # ;
721/// # assert_eq!(expected, items);
722/// ```
723///
724/// [`serde-xml-rs`]: https://docs.rs/serde-xml-rs
725/// [`untagged`]: https://serde.rs/enum-representations.html#untagged
726pub fn deserialize_ignore_any<'de, D: Deserializer<'de>, T: Default>(
727    deserializer: D,
728) -> Result<T, D::Error> {
729    IgnoredAny::deserialize(deserializer).map(|_| T::default())
730}