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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! De/Serialization for Rust's builtin and std types

use serde::{
    de::{Deserialize, DeserializeOwned, Deserializer, Error, MapAccess, SeqAccess, Visitor},
    ser::{Serialize, Serializer},
};
use std::{
    fmt::{self, Display},
    iter::FromIterator,
    marker::PhantomData,
    str::FromStr,
};
use Separator;

/// De/Serialize using [Display][] and [FromStr][] implementation
///
/// This allows to deserialize a string as a number.
/// It can be very useful for serialization formats like JSON, which do not support integer
/// numbers and have to resort to strings to represent them.
///
/// [Display]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html
/// [FromStr]: https://doc.rust-lang.org/stable/std/str/trait.FromStr.html
///
/// # Examples
///
/// ```
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// # use std::net::Ipv4Addr;
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde(with = "serde_with::rust::display_fromstr")]
///     address: Ipv4Addr,
///     #[serde(with = "serde_with::rust::display_fromstr")]
///     b: bool,
/// }
///
/// # fn main() {
/// let v: A = serde_json::from_str(r#"{
///     "address": "192.168.2.1",
///     "b": "true"
/// }"#).unwrap();
/// assert_eq!(Ipv4Addr::new(192, 168, 2, 1), v.address);
/// assert!(v.b);
///
/// let x = A {
///     address: Ipv4Addr::new(127, 53, 0, 1),
///     b: false,
/// };
/// assert_eq!(r#"{"address":"127.53.0.1","b":"false"}"#, serde_json::to_string(&x).unwrap());
/// # }
/// ```
pub mod display_fromstr {
    use super::*;
    use std::str::FromStr;

    /// Deserialize T using [FromStr]
    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
    where
        D: Deserializer<'de>,
        T: FromStr,
        T::Err: Display,
    {
        struct Helper<S>(PhantomData<S>);

        impl<'de, S> Visitor<'de> for Helper<S>
        where
            S: FromStr,
            <S as FromStr>::Err: Display,
        {
            type Value = S;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "valid json object")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                value.parse::<Self::Value>().map_err(Error::custom)
            }
        }

        deserializer.deserialize_str(Helper(PhantomData))
    }

    /// Serialize T using [Display]
    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Display,
        S: Serializer,
    {
        serializer.serialize_str(&*value.to_string())
    }
}

/// De/Serialize sequences using [FromIterator] and [IntoIterator] implementation for it and [Display][] and [FromStr][] implementation for each element
///
/// This allows to serialize and deserialize collections with elements which can be represented as strings.
///
/// [FromIterator]: https://doc.rust-lang.org/std/iter/trait.FromIterator.html
/// [IntoIterator]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html
/// [Display]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html
/// [FromStr]: https://doc.rust-lang.org/stable/std/str/trait.FromStr.html
///
/// # Examples
///
/// ```
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// # use std::net::Ipv4Addr;
/// # use std::collections::BTreeSet;
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde(with = "serde_with::rust::seq_display_fromstr")]
///     addresses: BTreeSet<Ipv4Addr>,
///     #[serde(with = "serde_with::rust::seq_display_fromstr")]
///     bs: Vec<bool>,
/// }
///
/// # fn main() {
/// let v: A = serde_json::from_str(r#"{
///     "addresses": ["192.168.2.1", "192.168.2.2", "192.168.1.1", "192.168.2.2"],
///     "bs": ["true", "false"]
/// }"#).unwrap();
/// assert_eq!(v.addresses.len(), 3);
/// assert!(v.addresses.contains(&Ipv4Addr::new(192, 168, 2, 1)));
/// assert!(v.addresses.contains(&Ipv4Addr::new(192, 168, 2, 2)));
/// assert!(!v.addresses.contains(&Ipv4Addr::new(192, 168, 1, 2)));
/// assert_eq!(v.bs.len(), 2);
/// assert!(v.bs[0]);
/// assert!(!v.bs[1]);
///
/// let x = A {
///     addresses: vec![
///         Ipv4Addr::new(127, 53, 0, 1),
///         Ipv4Addr::new(127, 53, 1, 1),
///         Ipv4Addr::new(127, 53, 0, 2)
///     ].into_iter().collect(),
///     bs: vec![false, true],
/// };
/// assert_eq!(r#"{"addresses":["127.53.0.1","127.53.0.2","127.53.1.1"],"bs":["false","true"]}"#, serde_json::to_string(&x).unwrap());
/// # }
/// ```
pub mod seq_display_fromstr {
    use serde::{
        de::{Deserializer, Error, SeqAccess, Visitor},
        ser::{SerializeSeq, Serializer},
    };
    use std::{
        fmt::{self, Display},
        iter::{FromIterator, IntoIterator},
        marker::PhantomData,
        str::FromStr,
    };

    /// Deserialize collection T using [FromIterator] and [FromStr] for each element
    pub fn deserialize<'de, D, T, I>(deserializer: D) -> Result<T, D::Error>
    where
        D: Deserializer<'de>,
        T: FromIterator<I> + Sized,
        I: FromStr,
        I::Err: Display,
    {
        struct Helper<S>(PhantomData<S>);

        impl<'de, S> Visitor<'de> for Helper<S>
        where
            S: FromStr,
            <S as FromStr>::Err: Display,
        {
            type Value = Vec<S>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "a sequence")
            }

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

                while let Some(value) = access.next_element::<&str>()? {
                    values.push(value.parse::<S>().map_err(Error::custom)?);
                }

                Ok(values)
            }
        }

        deserializer
            .deserialize_seq(Helper(PhantomData))
            .map(T::from_iter)
    }

    /// Serialize collection T using [IntoIterator] and [Display] for each element
    pub fn serialize<S, T, I>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        for<'a> &'a T: IntoIterator<Item = &'a I>,
        I: Display,
    {
        let iter = value.into_iter();
        let (_, to) = iter.size_hint();
        let mut seq = serializer.serialize_seq(to)?;
        for item in iter {
            seq.serialize_element(&item.to_string())?;
        }
        seq.end()
    }
}

/// De/Serialize a delimited collection using [Display][] and [FromStr][] implementation
///
/// You can define an arbitrary separator, by specifying a type which implements [Separator][].
/// Some common ones, like space and comma are already predefined and you can find them [here][Separator].
///
/// An empty string deserializes as an empty collection.
///
/// [Display]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html
/// [FromStr]: https://doc.rust-lang.org/stable/std/str/trait.FromStr.html
/// [Separator]: ../trait.Separator.html
///
/// # Examples
///
/// ```
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// use serde_with::{CommaSeparator, SpaceSeparator};
/// use std::collections::BTreeSet;
///
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde(with = "serde_with::rust::StringWithSeparator::<SpaceSeparator>")]
///     tags: Vec<String>,
///     #[serde(with = "serde_with::rust::StringWithSeparator::<CommaSeparator>")]
///     more_tags: BTreeSet<String>,
/// }
///
/// # fn main() {
/// let v: A = serde_json::from_str(r##"{
///     "tags": "#hello #world",
///     "more_tags": "foo,bar,bar"
/// }"##).unwrap();
/// assert_eq!(vec!["#hello", "#world"], v.tags);
/// assert_eq!(2, v.more_tags.len());
///
/// let x = A {
///     tags: vec!["1".to_string(), "2".to_string(), "3".to_string()],
///     more_tags: BTreeSet::new(),
/// };
/// assert_eq!(r#"{"tags":"1 2 3","more_tags":""}"#, serde_json::to_string(&x).unwrap());
/// # }
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
pub struct StringWithSeparator<Sep>(PhantomData<Sep>);

impl<Sep> StringWithSeparator<Sep>
where
    Sep: Separator,
{
    /// Serialize collection into a string with separator symbol
    pub fn serialize<S, T, V>(values: T, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: IntoIterator<Item = V>,
        V: Display,
    {
        let mut s = String::new();
        for v in values {
            s.push_str(&*v.to_string());
            s.push_str(Sep::separator());
        }
        serializer.serialize_str(if !s.is_empty() {
            // remove trailing separator if present
            &s[..s.len() - Sep::separator().len()]
        } else {
            &s[..]
        })
    }

    /// Deserialize a collection from a string with separator symbol
    pub fn deserialize<'de, D, T, V>(deserializer: D) -> Result<T, D::Error>
    where
        D: Deserializer<'de>,
        T: FromIterator<V>,
        V: FromStr,
        V::Err: Display,
    {
        let s = String::deserialize(deserializer)?;
        if s.is_empty() {
            Ok(None.into_iter().collect())
        } else {
            s.split(Sep::separator())
                .map(FromStr::from_str)
                .collect::<Result<_, _>>()
                .map_err(Error::custom)
        }
    }
}

/// 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.
///
/// # Examples
///
/// ```rust
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// # #[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>>,
/// }
/// # fn main() {
/// // 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());
/// # }
/// ```
#[cfg_attr(feature = "cargo-clippy", allow(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
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// # extern crate ron;
/// # #[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>,
/// }
/// # fn main() {
///
/// // Transparently add/remove Some() wrapper
/// # let pretty_config = ron::ser::PrettyConfig::default();
/// 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::default();
/// 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.
///
/// # Example
///
/// ```rust
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// # use std::{collections::HashSet, iter::FromIterator};
/// # #[derive(Debug, Eq, PartialEq)]
/// #[derive(Deserialize)]
/// struct Doc {
///     #[serde(with = "::serde_with::rust::sets_duplicate_value_is_error")]
///     set: HashSet<usize>,
/// }
/// # fn main() {
///
/// // 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());
/// # }
/// ```
pub mod sets_duplicate_value_is_error {
    use super::*;
    use 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(Error::custom("invalid entry: found duplicate value"));
                    };
                }

                Ok(values)
            }
        }

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

/// 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.
///
/// # Example
///
/// ```rust
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// # 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>,
/// }
/// # fn main() {
///
/// // 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());
/// # }
/// ```
pub mod maps_duplicate_key_is_error {
    use super::*;
    use 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(Error::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)
    }
}

/// Ensure that the first value is taken, if duplicate values exist
///
/// By default serde has a last-value-wins implementation, if duplicate keys for a set exist.
/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
pub mod sets_first_value_wins {
    use super::*;
    use duplicate_key_impls::DuplicateInsertsFirstWinsSet;

    /// 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: DuplicateInsertsFirstWinsSet<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: DuplicateInsertsFirstWinsSet<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.insert(value);
                }

                Ok(values)
            }
        }

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

/// 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.
///
/// # Example
///
/// ```rust
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
/// # 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>,
/// }
/// # fn main() {
///
/// // 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());
/// # }
/// ```
pub mod maps_first_key_wins {
    use super::*;
    use 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)
    }
}

/// De/Serialize a `Option<String>` type while transforming the empty string to `None`
///
/// Convert an `Option<T>` from/to string using `FromStr` and `AsRef<str>` implementations.
/// An empty string is deserialized as `None` and a `None` vice versa.
///
/// # Examples
///
/// ```
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # extern crate serde_json;
/// # extern crate serde_with;
///
/// #[derive(Deserialize, Serialize)]
/// struct A {
///     #[serde(with = "serde_with::rust::string_empty_as_none")]
///     tags: Option<String>,
/// }
///
/// # fn main() {
/// let v: A = serde_json::from_str(r##"{
///     "tags": ""
/// }"##).unwrap();
/// assert!(v.tags.is_none());
///
/// let v: A = serde_json::from_str(r##"{
///     "tags": "Hi"
/// }"##).unwrap();
/// assert_eq!(Some("Hi".to_string()), v.tags);
///
/// let x = A {
///     tags: Some("This is text".to_string()),
/// };
/// assert_eq!(r#"{"tags":"This is text"}"#, serde_json::to_string(&x).unwrap());
///
/// let x = A {
///     tags: None,
/// };
/// assert_eq!(r#"{"tags":""}"#, serde_json::to_string(&x).unwrap());
/// # }
/// ```
pub mod string_empty_as_none {
    use super::*;

    /// Deserialize an `Option<T>` from a string using `FromStr`
    pub fn deserialize<'de, D, S>(deserializer: D) -> Result<Option<S>, D::Error>
    where
        D: Deserializer<'de>,
        S: FromStr,
        S::Err: Display,
    {
        struct OptionStringEmptyNone<S>(PhantomData<S>);
        impl<'de, S> Visitor<'de> for OptionStringEmptyNone<S>
        where
            S: FromStr,
            S::Err: Display,
        {
            type Value = Option<S>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("any string")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                match value {
                    "" => Ok(None),
                    v => S::from_str(v).map(Some).map_err(Error::custom),
                }
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: Error,
            {
                match &*value {
                    "" => Ok(None),
                    v => S::from_str(v).map(Some).map_err(Error::custom),
                }
            }

            // handles the `null` case
            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: Error,
            {
                Ok(None)
            }
        }

        deserializer.deserialize_any(OptionStringEmptyNone(PhantomData))
    }

    /// Serialize a string from `Option<T>` using `AsRef<str>` or using the empty string if `None`.
    pub fn serialize<T, S>(option: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: AsRef<str>,
        S: Serializer,
    {
        if let Some(value) = option {
            value.as_ref().serialize(serializer)
        } else {
            "".serialize(serializer)
        }
    }
}