1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! De/Serialization for Rust's builtin and std types

use crate::prelude::*;

/// Makes a distinction between a missing, unset, or existing value
///
/// Some serialization formats make a distinction between missing fields, fields with a `null`
/// value, and existing values. One such format is JSON. By default it is not easily possible to
/// differentiate between a missing value and a field which is `null`, as they deserialize to the
/// same value. This helper changes it, by using an `Option<Option<T>>` to deserialize into.
///
/// * `None`: Represents a missing value.
/// * `Some(None)`: Represents a `null` value.
/// * `Some(Some(value))`: Represents an existing value.
///
/// Note: This cannot be made compatible to `serde_as`, since skipping of values is only available on the field level.
/// A hypothetical `DoubleOption<T>` with a `SerializeAs` implementation would allow writing something like this.
/// This cannot work, since there is no way to tell the `Vec` to skip the inner `DoubleOption` if it is `None`.
///
/// ```rust
/// # #[cfg(FALSE)] {
/// # struct Foobar {
/// #[serde_as(as = "Vec<DoubleOption<_>>")]
/// data: Vec<Option<Option<i32>>>,
/// # }
/// # }
/// ```
///
/// # Examples
///
/// ```rust
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Debug, PartialEq, Eq)]
/// #[derive(Deserialize, Serialize)]
/// struct Doc {
///     #[serde(
///         default,                                    // <- important for deserialization
///         skip_serializing_if = "Option::is_none",    // <- important for serialization
///         with = "::serde_with::rust::double_option",
///     )]
///     a: Option<Option<u8>>,
/// }
/// // Missing Value
/// let s = r#"{}"#;
/// assert_eq!(Doc { a: None }, serde_json::from_str(s).unwrap());
/// assert_eq!(s, serde_json::to_string(&Doc { a: None }).unwrap());
///
/// // Unset Value
/// let s = r#"{"a":null}"#;
/// assert_eq!(Doc { a: Some(None) }, serde_json::from_str(s).unwrap());
/// assert_eq!(s, serde_json::to_string(&Doc { a: Some(None) }).unwrap());
///
/// // Existing Value
/// let s = r#"{"a":5}"#;
/// assert_eq!(Doc { a: Some(Some(5)) }, serde_json::from_str(s).unwrap());
/// assert_eq!(s, serde_json::to_string(&Doc { a: Some(Some(5)) }).unwrap());
/// ```
#[allow(clippy::option_option)]
pub mod double_option {
    use super::*;

    /// Deserialize potentially non-existing optional value
    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
    where
        T: Deserialize<'de>,
        D: Deserializer<'de>,
    {
        Deserialize::deserialize(deserializer).map(Some)
    }

    /// Serialize optional value
    pub fn serialize<S, T>(values: &Option<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: Serialize,
    {
        match values {
            None => serializer.serialize_unit(),
            Some(None) => serializer.serialize_none(),
            Some(Some(v)) => serializer.serialize_some(&v),
        }
    }
}

/// Serialize inner value if [`Some`]`(T)`. If [`None`], serialize the unit struct `()`.
///
/// When used in conjunction with `skip_serializing_if = "Option::is_none"` and
/// `default`, you can build an optional value by skipping if it is [`None`], or serializing its
/// inner value if [`Some`]`(T)`.
///
/// Not all serialization formats easily support optional values.
/// While JSON uses the [`Option`] type to represent optional values and only serializes the inner
/// part of the [`Some`]`()`, other serialization formats, such as [RON][], choose to serialize the
/// [`Some`] around a value.
/// This helper helps building a truly optional value for such serializers.
///
/// [RON]: https://github.com/ron-rs/ron
///
/// # Example
///
/// ```rust
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Debug, Eq, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Doc {
///     mandatory: usize,
///     #[serde(
///         default,                                    // <- important for deserialization
///         skip_serializing_if = "Option::is_none",    // <- important for serialization
///         with = "::serde_with::rust::unwrap_or_skip",
///     )]
///     optional: Option<usize>,
/// }
///
/// // Transparently add/remove Some() wrapper
/// # let pretty_config = ron::ser::PrettyConfig::new()
/// #     .new_line("\n".into());
/// let s = r#"(
///     mandatory: 1,
///     optional: 2,
/// )"#;
/// let v = Doc {
///     mandatory: 1,
///     optional: Some(2),
/// };
/// assert_eq!(v, ron::de::from_str(s).unwrap());
/// assert_eq!(s, ron::ser::to_string_pretty(&v, pretty_config).unwrap());
///
/// // Missing values are deserialized as `None`
/// // while `None` values are skipped during serialization.
/// # let pretty_config = ron::ser::PrettyConfig::new()
/// #     .new_line("\n".into());
/// let s = r#"(
///     mandatory: 1,
/// )"#;
/// let v = Doc {
///     mandatory: 1,
///     optional: None,
/// };
/// assert_eq!(v, ron::de::from_str(s).unwrap());
/// assert_eq!(s, ron::ser::to_string_pretty(&v, pretty_config).unwrap());
/// ```
pub mod unwrap_or_skip {
    use super::*;

    /// Deserialize value wrapped in Some(T)
    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
    where
        D: Deserializer<'de>,
        T: DeserializeOwned,
    {
        T::deserialize(deserializer).map(Some)
    }

    /// Serialize value if Some(T), unit struct if None
    pub fn serialize<T, S>(option: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Serialize,
        S: Serializer,
    {
        if let Some(value) = option {
            value.serialize(serializer)
        } else {
            ().serialize(serializer)
        }
    }
}

/// Ensure no duplicate values exist in a set.
///
/// By default serde has a last-value-wins implementation, if duplicate values for a set exist.
/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
/// and it can indicate an error in the serialized data.
///
/// This helper returns an error if two identical values exist in a set.
///
/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
///
/// # Converting to `serde_as`
///
/// The same functionality can be more clearly expressed using the `serde_as` macro and [`SetPreventDuplicates`].
/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
///
/// ```rust
/// # #[cfg(FALSE)] {
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde_as(as = "SetPreventDuplicates<_, _>")]
///     s: HashSet<usize>,
/// }
/// # }
/// ```
///
/// [`HashSet`]: std::collections::HashSet
/// [`BTreeSet`]: std::collections::HashSet
///
/// # Example
///
/// ```rust
/// # use std::collections::HashSet;
/// # use serde::Deserialize;
/// #
/// # #[derive(Debug, Eq, PartialEq)]
/// #[derive(Deserialize)]
/// struct Doc {
///     #[serde(with = "::serde_with::rust::sets_duplicate_value_is_error")]
///     set: HashSet<usize>,
/// }
///
/// // Sets are serialized normally,
/// let s = r#"{"set": [1, 2, 3, 4]}"#;
/// let v = Doc {
///     set: HashSet::from_iter(vec![1, 2, 3, 4]),
/// };
/// assert_eq!(v, serde_json::from_str(s).unwrap());
///
/// // but create an error if duplicate values, like the `1`, exist.
/// let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
/// let res: Result<Doc, _> = serde_json::from_str(s);
/// assert!(res.is_err());
/// ```
#[cfg(feature = "alloc")]
pub mod sets_duplicate_value_is_error {
    use super::*;
    use crate::duplicate_key_impls::PreventDuplicateInsertsSet;

    /// Deserialize a set and return an error on duplicate values
    pub fn deserialize<'de, D, T, V>(deserializer: D) -> Result<T, D::Error>
    where
        T: PreventDuplicateInsertsSet<V>,
        V: Deserialize<'de>,
        D: Deserializer<'de>,
    {
        struct SeqVisitor<T, V> {
            marker: PhantomData<T>,
            set_item_type: PhantomData<V>,
        }

        impl<'de, T, V> Visitor<'de> for SeqVisitor<T, V>
        where
            T: PreventDuplicateInsertsSet<V>,
            V: Deserialize<'de>,
        {
            type Value = T;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a sequence")
            }

            #[inline]
            fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut values = Self::Value::new(access.size_hint());

                while let Some(value) = access.next_element()? {
                    if !values.insert(value) {
                        return Err(DeError::custom("invalid entry: found duplicate value"));
                    };
                }

                Ok(values)
            }
        }

        let visitor = SeqVisitor {
            marker: PhantomData,
            set_item_type: PhantomData,
        };
        deserializer.deserialize_seq(visitor)
    }

    /// Serialize the set with the default serializer
    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Serialize,
        S: Serializer,
    {
        value.serialize(serializer)
    }
}

/// Ensure no duplicate keys exist in a map.
///
/// By default serde has a last-value-wins implementation, if duplicate keys for a map exist.
/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
/// and it can indicate an error in the serialized data.
///
/// This helper returns an error if two identical keys exist in a map.
///
/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
///
/// # Converting to `serde_as`
///
/// The same functionality can be more clearly expressed using the `serde_as` macro and [`MapPreventDuplicates`].
/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
///
/// ```rust
/// # #[cfg(FALSE)] {
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde_as(as = "MapPreventDuplicates<_, _>")]
///     s: HashMap<usize, usize>,
/// }
/// # }
/// ```
///
/// [`HashMap`]: std::collections::HashMap
/// [`BTreeMap`]: std::collections::HashMap
///
/// # Example
///
/// ```rust
/// # use serde::Deserialize;
/// # use std::collections::HashMap;
/// #
/// # #[derive(Debug, Eq, PartialEq)]
/// #[derive(Deserialize)]
/// struct Doc {
///     #[serde(with = "::serde_with::rust::maps_duplicate_key_is_error")]
///     map: HashMap<usize, usize>,
/// }
///
/// // Maps are serialized normally,
/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
/// let mut v = Doc {
///     map: HashMap::new(),
/// };
/// v.map.insert(1, 1);
/// v.map.insert(2, 2);
/// v.map.insert(3, 3);
/// assert_eq!(v, serde_json::from_str(s).unwrap());
///
/// // but create an error if duplicate keys, like the `1`, exist.
/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
/// let res: Result<Doc, _> = serde_json::from_str(s);
/// assert!(res.is_err());
/// ```
#[cfg(feature = "alloc")]
pub mod maps_duplicate_key_is_error {
    use super::*;
    use crate::duplicate_key_impls::PreventDuplicateInsertsMap;

    /// Deserialize a map and return an error on duplicate keys
    pub fn deserialize<'de, D, T, K, V>(deserializer: D) -> Result<T, D::Error>
    where
        T: PreventDuplicateInsertsMap<K, V>,
        K: Deserialize<'de>,
        V: Deserialize<'de>,
        D: Deserializer<'de>,
    {
        struct MapVisitor<T, K, V> {
            marker: PhantomData<T>,
            map_key_type: PhantomData<K>,
            map_value_type: PhantomData<V>,
        }

        impl<'de, T, K, V> Visitor<'de> for MapVisitor<T, K, V>
        where
            T: PreventDuplicateInsertsMap<K, V>,
            K: Deserialize<'de>,
            V: Deserialize<'de>,
        {
            type Value = T;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a map")
            }

            #[inline]
            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut values = Self::Value::new(access.size_hint());

                while let Some((key, value)) = access.next_entry()? {
                    if !values.insert(key, value) {
                        return Err(DeError::custom("invalid entry: found duplicate key"));
                    };
                }

                Ok(values)
            }
        }

        let visitor = MapVisitor {
            marker: PhantomData,
            map_key_type: PhantomData,
            map_value_type: PhantomData,
        };
        deserializer.deserialize_map(visitor)
    }

    /// Serialize the map with the default serializer
    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Serialize,
        S: Serializer,
    {
        value.serialize(serializer)
    }
}

/// Ensure that the last value is taken, if duplicate values exist
///
/// By default serde has a first-value-wins implementation, if duplicate keys for a set exist.
/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
///
/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
///
/// # Converting to `serde_as`
///
/// The same functionality can be more clearly expressed using the `serde_as` macro and [`SetLastValueWins`].
/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
///
/// ```rust
/// # #[cfg(FALSE)] {
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde_as(as = "SetLastValueWins<_, _>")]
///     s: HashSet<usize>,
/// }
/// # }
/// ```
///
/// [`HashSet`]: std::collections::HashSet
/// [`BTreeSet`]: std::collections::HashSet
#[cfg(feature = "alloc")]
pub mod sets_last_value_wins {
    use super::*;
    use crate::duplicate_key_impls::DuplicateInsertsLastWinsSet;

    /// Deserialize a set and keep the last of equal values
    pub fn deserialize<'de, D, T, V>(deserializer: D) -> Result<T, D::Error>
    where
        T: DuplicateInsertsLastWinsSet<V>,
        V: Deserialize<'de>,
        D: Deserializer<'de>,
    {
        struct SeqVisitor<T, V> {
            marker: PhantomData<T>,
            set_item_type: PhantomData<V>,
        }

        impl<'de, T, V> Visitor<'de> for SeqVisitor<T, V>
        where
            T: DuplicateInsertsLastWinsSet<V>,
            V: Deserialize<'de>,
        {
            type Value = T;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a sequence")
            }

            #[inline]
            fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut values = Self::Value::new(access.size_hint());

                while let Some(value) = access.next_element()? {
                    values.replace(value);
                }

                Ok(values)
            }
        }

        let visitor = SeqVisitor {
            marker: PhantomData,
            set_item_type: PhantomData,
        };
        deserializer.deserialize_seq(visitor)
    }

    /// Serialize the set with the default serializer
    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Serialize,
        S: Serializer,
    {
        value.serialize(serializer)
    }
}

/// Ensure that the first key is taken, if duplicate keys exist
///
/// By default serde has a last-key-wins implementation, if duplicate keys for a map exist.
/// Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
///
/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
///
/// [`HashMap`]: std::collections::HashMap
/// [`BTreeMap`]: std::collections::HashMap
///
/// # Converting to `serde_as`
///
/// The same functionality can be more clearly expressed using the `serde_as` macro and [`MapFirstKeyWins`].
/// The `_` is a placeholder which works for any type which implements [`Serialize`]/[`Deserialize`].
///
/// ```rust
/// # #[cfg(FALSE)] {
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde_as(as = "MapFirstKeyWins<_, _>")]
///     s: HashMap<usize, usize>,
/// }
/// # }
/// ```
///
/// # Example
///
/// ```rust
/// # use serde::Deserialize;
/// # use std::collections::HashMap;
/// #
/// # #[derive(Debug, Eq, PartialEq)]
/// #[derive(Deserialize)]
/// struct Doc {
///     #[serde(with = "::serde_with::rust::maps_first_key_wins")]
///     map: HashMap<usize, usize>,
/// }
///
/// // Maps are serialized normally,
/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
/// let mut v = Doc {
///     map: HashMap::new(),
/// };
/// v.map.insert(1, 1);
/// v.map.insert(2, 2);
/// v.map.insert(3, 3);
/// assert_eq!(v, serde_json::from_str(s).unwrap());
///
/// // but create an error if duplicate keys, like the `1`, exist.
/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
/// let mut v = Doc {
///     map: HashMap::new(),
/// };
/// v.map.insert(1, 1);
/// v.map.insert(2, 2);
/// assert_eq!(v, serde_json::from_str(s).unwrap());
/// ```
#[cfg(feature = "alloc")]
pub mod maps_first_key_wins {
    use super::*;
    use crate::duplicate_key_impls::DuplicateInsertsFirstWinsMap;

    /// Deserialize a map and return an error on duplicate keys
    pub fn deserialize<'de, D, T, K, V>(deserializer: D) -> Result<T, D::Error>
    where
        T: DuplicateInsertsFirstWinsMap<K, V>,
        K: Deserialize<'de>,
        V: Deserialize<'de>,
        D: Deserializer<'de>,
    {
        struct MapVisitor<T, K, V> {
            marker: PhantomData<T>,
            map_key_type: PhantomData<K>,
            map_value_type: PhantomData<V>,
        }

        impl<'de, T, K, V> Visitor<'de> for MapVisitor<T, K, V>
        where
            T: DuplicateInsertsFirstWinsMap<K, V>,
            K: Deserialize<'de>,
            V: Deserialize<'de>,
        {
            type Value = T;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a map")
            }

            #[inline]
            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut values = Self::Value::new(access.size_hint());

                while let Some((key, value)) = access.next_entry()? {
                    values.insert(key, value);
                }

                Ok(values)
            }
        }

        let visitor = MapVisitor {
            marker: PhantomData,
            map_key_type: PhantomData,
            map_value_type: PhantomData,
        };
        deserializer.deserialize_map(visitor)
    }

    /// Serialize the map with the default serializer
    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Serialize,
        S: Serializer,
    {
        value.serialize(serializer)
    }
}

/// Deserialize any value, ignore it, and return the default value for the type being deserialized.
///
/// This function can be used in two different ways:
///
/// 1. It is useful for instance to create an enum with a catch-all variant that will accept any incoming data.
/// 2. [`untagged`] enum representations do not allow the `other` annotation as the fallback enum variant.
///     With this function you can emulate an `other` variant, which can deserialize any data carrying enum.
///
/// **Note:** Using this function will prevent deserializing data-less enum variants.
/// If this is a problem depends on the data format.
/// For example, deserializing `"Bar"` as an enum in JSON would fail, since it carries no data.
///
/// # Examples
///
/// ## Deserializing a heterogeneous collection of XML nodes
///
/// When [`serde-xml-rs`] deserializes an XML tag to an enum, it always maps the tag
/// name to the enum variant name, and the tag attributes and children to the enum contents.
/// This means that in order for an enum variant to accept any XML tag, it both has to use
/// `#[serde(other)]` to accept any tag name, and `#[serde(deserialize_with = "deserialize_ignore_any")]`
/// to accept any attributes and children.
///
/// ```rust
/// # use serde::Deserialize;
/// use serde_with::rust::deserialize_ignore_any;
///
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize)]
/// #[serde(rename_all = "lowercase")]
/// enum Item {
///     Foo(String),
///     Bar(String),
///     #[serde(other, deserialize_with = "deserialize_ignore_any")]
///     Other,
/// }
///
/// // Deserialize this XML
/// # let items: Vec<Item> = serde_xml_rs::from_str(
/// r"
/// <foo>a</foo>
/// <bar>b</bar>
/// <foo>c</foo>
/// <unknown>d</unknown>
/// "
/// # ).unwrap();
///
/// // into these Items
/// # let expected =
/// vec![
///     Item::Foo(String::from("a")),
///     Item::Bar(String::from("b")),
///     Item::Foo(String::from("c")),
///     Item::Other,
/// ]
/// # ;
/// # assert_eq!(expected, items);
/// ```
///
/// ## Simulating an `other` enum variant in an `untagged` enum
///
/// ```rust
/// # use serde::Deserialize;
/// # use serde_json::json;
/// use serde_with::rust::deserialize_ignore_any;
///
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize)]
/// #[serde(untagged)]
/// enum Item {
///     Foo{x: u8},
///     #[serde(deserialize_with = "deserialize_ignore_any")]
///     Other,
/// }
///
/// // Deserialize this JSON
/// # let items: Vec<Item> = serde_json::from_value(
/// json!([
///     {"y": 1},
///     {"x": 1},
/// ])
/// # ).unwrap();
///
/// // into these Items
/// # let expected =
/// vec![Item::Other, Item::Foo{x: 1}]
/// # ;
/// # assert_eq!(expected, items);
/// ```
///
/// [`serde-xml-rs`]: https://docs.rs/serde-xml-rs
/// [`untagged`]: https://serde.rs/enum-representations.html#untagged
pub fn deserialize_ignore_any<'de, D: Deserializer<'de>, T: Default>(
    deserializer: D,
) -> Result<T, D::Error> {
    IgnoredAny::deserialize(deserializer).map(|_| T::default())
}