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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! Logic for serde-compatible serialization.
use crate::{types::Value, Error};
use serde::{ser, Serialize};
use std::{collections::HashMap, iter::once};

#[derive(Clone, Default)]
pub struct Serializer {}

pub struct SeqSerializer {
    items: Vec<Value>,
}

pub struct SeqVariantSerializer<'a> {
    index: u32,
    variant: &'a str,
    items: Vec<Value>,
}

pub struct MapSerializer {
    indices: HashMap<String, usize>,
    values: Vec<Value>,
}

pub struct StructSerializer {
    fields: Vec<(String, Value)>,
}

pub struct StructVariantSerializer<'a> {
    index: u32,
    variant: &'a str,
    fields: Vec<(String, Value)>,
}

impl SeqSerializer {
    pub fn new(len: Option<usize>) -> SeqSerializer {
        let items = match len {
            Some(len) => Vec::with_capacity(len),
            None => Vec::new(),
        };

        SeqSerializer { items }
    }
}

impl<'a> SeqVariantSerializer<'a> {
    pub fn new(index: u32, variant: &'a str, len: Option<usize>) -> SeqVariantSerializer {
        let items = match len {
            Some(len) => Vec::with_capacity(len),
            None => Vec::new(),
        };
        SeqVariantSerializer {
            index,
            variant,
            items,
        }
    }
}

impl MapSerializer {
    pub fn new(len: Option<usize>) -> MapSerializer {
        let (indices, values) = match len {
            Some(len) => (HashMap::with_capacity(len), Vec::with_capacity(len)),
            None => (HashMap::new(), Vec::new()),
        };

        MapSerializer { indices, values }
    }
}

impl StructSerializer {
    pub fn new(len: usize) -> StructSerializer {
        StructSerializer {
            fields: Vec::with_capacity(len),
        }
    }
}

impl<'a> StructVariantSerializer<'a> {
    pub fn new(index: u32, variant: &'a str, len: usize) -> StructVariantSerializer {
        StructVariantSerializer {
            index,
            variant,
            fields: Vec::with_capacity(len),
        }
    }
}

impl<'b> ser::Serializer for &'b mut Serializer {
    type Ok = Value;
    type Error = Error;
    type SerializeSeq = SeqSerializer;
    type SerializeTuple = SeqSerializer;
    type SerializeTupleStruct = SeqSerializer;
    type SerializeTupleVariant = SeqVariantSerializer<'b>;
    type SerializeMap = MapSerializer;
    type SerializeStruct = StructSerializer;
    type SerializeStructVariant = StructVariantSerializer<'b>;

    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Boolean(v))
    }

    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
        self.serialize_i32(i32::from(v))
    }

    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
        self.serialize_i32(i32::from(v))
    }

    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Int(v))
    }

    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Long(v))
    }

    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
        self.serialize_i32(i32::from(v))
    }

    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
        self.serialize_i32(i32::from(v))
    }

    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
        if v <= i32::MAX as u32 {
            self.serialize_i32(v as i32)
        } else {
            self.serialize_i64(i64::from(v))
        }
    }

    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
        if v <= i64::MAX as u64 {
            self.serialize_i64(v as i64)
        } else {
            Err(ser::Error::custom("u64 is too large"))
        }
    }

    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Float(v))
    }

    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Double(v))
    }

    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
        self.serialize_str(&once(v).collect::<String>())
    }

    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
        Ok(Value::String(v.to_owned()))
    }

    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Bytes(v.to_owned()))
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Ok(Value::from(None::<Self::Ok>))
    }

    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        let v = value.serialize(&mut Serializer::default())?;
        Ok(Value::from(Some(v)))
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Null)
    }

    fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
        self.serialize_unit()
    }

    fn serialize_unit_variant(
        self,
        _: &'static str,
        index: u32,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Enum(index, variant.to_string()))
    }

    fn serialize_newtype_struct<T: ?Sized>(
        self,
        _: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T: ?Sized>(
        self,
        _: &'static str,
        index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        Ok(Value::Record(vec![
            ("type".to_owned(), Value::Enum(index, variant.to_owned())),
            (
                "value".to_owned(),
                Value::Union(index, Box::new(value.serialize(self)?)),
            ),
        ]))
    }

    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Ok(SeqSerializer::new(len))
    }

    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_struct(
        self,
        _: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_variant(
        self,
        _: &'static str,
        index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Ok(SeqVariantSerializer::new(index, variant, Some(len)))
    }

    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Ok(MapSerializer::new(len))
    }

    fn serialize_struct(
        self,
        _: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Ok(StructSerializer::new(len))
    }

    fn serialize_struct_variant(
        self,
        _: &'static str,
        index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Ok(StructVariantSerializer::new(index, variant, len))
    }

    fn is_human_readable(&self) -> bool {
        crate::util::is_human_readable()
    }
}

impl ser::SerializeSeq for SeqSerializer {
    type Ok = Value;
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        self.items
            .push(value.serialize(&mut Serializer::default())?);
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Array(self.items))
    }
}

impl ser::SerializeTuple for SeqSerializer {
    type Ok = Value;
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        ser::SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        ser::SerializeSeq::end(self)
    }
}

impl ser::SerializeTupleStruct for SeqSerializer {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        ser::SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        ser::SerializeSeq::end(self)
    }
}

impl<'a> ser::SerializeSeq for SeqVariantSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        self.items.push(Value::Union(
            self.index,
            Box::new(value.serialize(&mut Serializer::default())?),
        ));
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Record(vec![
            (
                "type".to_owned(),
                Value::Enum(self.index, self.variant.to_owned()),
            ),
            ("value".to_owned(), Value::Array(self.items)),
        ]))
    }
}

impl<'a> ser::SerializeTupleVariant for SeqVariantSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        ser::SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        ser::SerializeSeq::end(self)
    }
}

impl ser::SerializeMap for MapSerializer {
    type Ok = Value;
    type Error = Error;

    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        let key = key.serialize(&mut Serializer::default())?;

        if let Value::String(key) = key {
            self.indices.insert(key, self.values.len());
            Ok(())
        } else {
            Err(ser::Error::custom("map key is not a string"))
        }
    }

    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        self.values
            .push(value.serialize(&mut Serializer::default())?);
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        let mut items = HashMap::new();
        for (key, index) in self.indices {
            if let Some(value) = self.values.get(index) {
                items.insert(key, value.clone());
            }
        }

        Ok(Value::Map(items))
    }
}

impl ser::SerializeStruct for StructSerializer {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T: ?Sized>(
        &mut self,
        name: &'static str,
        value: &T,
    ) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        self.fields.push((
            name.to_owned(),
            value.serialize(&mut Serializer::default())?,
        ));
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Record(self.fields))
    }
}

impl<'a> ser::SerializeStructVariant for StructVariantSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T: ?Sized>(
        &mut self,
        name: &'static str,
        value: &T,
    ) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        self.fields.push((
            name.to_owned(),
            value.serialize(&mut Serializer::default())?,
        ));
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(Value::Record(vec![
            (
                "type".to_owned(),
                Value::Enum(self.index, self.variant.to_owned()),
            ),
            (
                "value".to_owned(),
                Value::Union(self.index, Box::new(Value::Record(self.fields))),
            ),
        ]))
    }
}

/// Interpret a serializeable instance as a `Value`.
///
/// This conversion can fail if the value is not valid as per the Avro specification.
/// e.g: HashMap with non-string keys
pub fn to_value<S: Serialize>(value: S) -> Result<Value, Error> {
    let mut serializer = Serializer::default();
    value.serialize(&mut serializer)
}

#[cfg(test)]
mod tests {
    use super::*;
    use apache_avro_test_helper::TestResult;
    use pretty_assertions::assert_eq;
    use serde::{Deserialize, Serialize};
    use std::sync::atomic::Ordering;

    #[derive(Debug, Deserialize, Serialize, Clone)]
    struct Test {
        a: i64,
        b: String,
    }

    #[derive(Debug, Deserialize, Serialize)]
    struct TestInner {
        a: Test,
        b: i32,
    }

    #[derive(Debug, Deserialize, Serialize)]
    struct TestUnitExternalEnum {
        a: UnitExternalEnum,
    }

    #[derive(Debug, Deserialize, Serialize)]
    enum UnitExternalEnum {
        Val1,
        Val2,
    }

    #[derive(Debug, Deserialize, Serialize)]
    struct TestUnitInternalEnum {
        a: UnitInternalEnum,
    }

    #[derive(Debug, Deserialize, Serialize)]
    #[serde(tag = "t")]
    enum UnitInternalEnum {
        Val1,
        Val2,
    }

    #[derive(Debug, Deserialize, Serialize)]
    struct TestUnitAdjacentEnum {
        a: UnitAdjacentEnum,
    }

    #[derive(Debug, Deserialize, Serialize)]
    #[serde(tag = "t", content = "v")]
    enum UnitAdjacentEnum {
        Val1,
        Val2,
    }

    #[derive(Debug, Deserialize, Serialize)]
    struct TestUnitUntaggedEnum {
        a: UnitUntaggedEnum,
    }

    #[derive(Debug, Deserialize, Serialize)]
    #[serde(untagged)]
    enum UnitUntaggedEnum {
        Val1,
        Val2,
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestSingleValueExternalEnum {
        a: SingleValueExternalEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    enum SingleValueExternalEnum {
        Double(f64),
        String(String),
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestSingleValueInternalEnum {
        a: SingleValueInternalEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(tag = "t")]
    enum SingleValueInternalEnum {
        Double(f64),
        String(String),
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestSingleValueAdjacentEnum {
        a: SingleValueAdjacentEnum,
    }
    #[derive(Debug, Serialize, Deserialize)]
    #[serde(tag = "t", content = "v")]
    enum SingleValueAdjacentEnum {
        Double(f64),
        String(String),
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestSingleValueUntaggedEnum {
        a: SingleValueUntaggedEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(untagged)]
    enum SingleValueUntaggedEnum {
        Double(f64),
        String(String),
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestStructExternalEnum {
        a: StructExternalEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    enum StructExternalEnum {
        Val1 { x: f32, y: f32 },
        Val2 { x: f32, y: f32 },
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestStructInternalEnum {
        a: StructInternalEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(tag = "type")]
    enum StructInternalEnum {
        Val1 { x: f32, y: f32 },
        Val2 { x: f32, y: f32 },
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestStructAdjacentEnum {
        a: StructAdjacentEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(tag = "t", content = "v")]
    enum StructAdjacentEnum {
        Val1 { x: f32, y: f32 },
        Val2 { x: f32, y: f32 },
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestStructUntaggedEnum {
        a: StructUntaggedEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(untagged)]
    enum StructUntaggedEnum {
        Val1 { x: f32, y: f32 },
        Val2 { x: f32, y: f32, z: f32 },
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestTupleExternalEnum {
        a: TupleExternalEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    enum TupleExternalEnum {
        Val1(f32, f32),
        Val2(f32, f32, f32),
    }

    // Tuple Internal Enum cannot be instantiated

    #[derive(Debug, Serialize, Deserialize)]
    struct TestTupleAdjacentEnum {
        a: TupleAdjacentEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(tag = "t", content = "v")]
    enum TupleAdjacentEnum {
        Val1(f32, f32),
        Val2(f32, f32, f32),
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct TestTupleUntaggedEnum {
        a: TupleUntaggedEnum,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(untagged)]
    enum TupleUntaggedEnum {
        Val1(f32, f32),
        Val2(f32, f32, f32),
    }

    #[test]
    fn test_to_value() -> TestResult {
        let test = Test {
            a: 27,
            b: "foo".to_owned(),
        };
        let expected = Value::Record(vec![
            ("a".to_owned(), Value::Long(27)),
            ("b".to_owned(), Value::String("foo".to_owned())),
        ]);

        assert_eq!(to_value(test.clone())?, expected);

        let test_inner = TestInner { a: test, b: 35 };

        let expected_inner = Value::Record(vec![
            (
                "a".to_owned(),
                Value::Record(vec![
                    ("a".to_owned(), Value::Long(27)),
                    ("b".to_owned(), Value::String("foo".to_owned())),
                ]),
            ),
            ("b".to_owned(), Value::Int(35)),
        ]);

        assert_eq!(to_value(test_inner)?, expected_inner);

        Ok(())
    }

    #[test]
    fn test_to_value_unit_enum() -> TestResult {
        let test = TestUnitExternalEnum {
            a: UnitExternalEnum::Val1,
        };

        let expected = Value::Record(vec![("a".to_owned(), Value::Enum(0, "Val1".to_owned()))]);

        assert_eq!(
            to_value(test)?,
            expected,
            "Error serializing unit external enum"
        );

        let test = TestUnitInternalEnum {
            a: UnitInternalEnum::Val1,
        };

        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![("t".to_owned(), Value::String("Val1".to_owned()))]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "Error serializing unit internal enum"
        );

        let test = TestUnitAdjacentEnum {
            a: UnitAdjacentEnum::Val1,
        };

        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![("t".to_owned(), Value::String("Val1".to_owned()))]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "Error serializing unit adjacent enum"
        );

        let test = TestUnitUntaggedEnum {
            a: UnitUntaggedEnum::Val1,
        };

        let expected = Value::Record(vec![("a".to_owned(), Value::Null)]);

        assert_eq!(
            to_value(test)?,
            expected,
            "Error serializing unit untagged enum"
        );

        Ok(())
    }

    #[test]
    fn test_to_value_single_value_enum() -> TestResult {
        let test = TestSingleValueExternalEnum {
            a: SingleValueExternalEnum::Double(64.0),
        };

        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("type".to_owned(), Value::Enum(0, "Double".to_owned())),
                (
                    "value".to_owned(),
                    Value::Union(0, Box::new(Value::Double(64.0))),
                ),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "Error serializing single value external enum"
        );

        // It is not possible to serialize an internal Single Value enum...
        let test = TestSingleValueInternalEnum {
            a: SingleValueInternalEnum::Double(64.0),
        };

        assert!(to_value(test).is_err(), "{}", true);

        let test = TestSingleValueAdjacentEnum {
            a: SingleValueAdjacentEnum::Double(64.0),
        };

        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("t".to_owned(), Value::String("Double".to_owned())),
                ("v".to_owned(), Value::Double(64.0)),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "Error serializing single value adjacent enum"
        );

        let test = TestSingleValueUntaggedEnum {
            a: SingleValueUntaggedEnum::Double(64.0),
        };

        let expected = Value::Record(vec![("a".to_owned(), Value::Double(64.0))]);

        assert_eq!(
            to_value(test)?,
            expected,
            "Error serializing single value untagged enum"
        );

        Ok(())
    }

    #[test]
    fn test_to_value_struct_enum() -> TestResult {
        let test = TestStructExternalEnum {
            a: StructExternalEnum::Val1 { x: 1.0, y: 2.0 },
        };
        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("type".to_owned(), Value::Enum(0, "Val1".to_owned())),
                (
                    "value".to_owned(),
                    Value::Union(
                        0,
                        Box::new(Value::Record(vec![
                            ("x".to_owned(), Value::Float(1.0)),
                            ("y".to_owned(), Value::Float(2.0)),
                        ])),
                    ),
                ),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing struct external enum"
        );

        // I don't think that this is feasible in avro

        let test = TestStructInternalEnum {
            a: StructInternalEnum::Val1 { x: 1.0, y: 2.0 },
        };
        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("type".to_owned(), Value::String("Val1".to_owned())),
                ("x".to_owned(), Value::Float(1.0)),
                ("y".to_owned(), Value::Float(2.0)),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing struct internal enum"
        );

        let test = TestStructAdjacentEnum {
            a: StructAdjacentEnum::Val1 { x: 1.0, y: 2.0 },
        };
        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("t".to_owned(), Value::String("Val1".to_owned())),
                (
                    "v".to_owned(),
                    Value::Record(vec![
                        ("x".to_owned(), Value::Float(1.0)),
                        ("y".to_owned(), Value::Float(2.0)),
                    ]),
                ),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing struct adjacent enum"
        );

        let test = TestStructUntaggedEnum {
            a: StructUntaggedEnum::Val1 { x: 1.0, y: 2.0 },
        };
        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("x".to_owned(), Value::Float(1.0)),
                ("y".to_owned(), Value::Float(2.0)),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing struct untagged enum"
        );

        let test = TestStructUntaggedEnum {
            a: StructUntaggedEnum::Val2 {
                x: 1.0,
                y: 2.0,
                z: 3.0,
            },
        };
        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("x".to_owned(), Value::Float(1.0)),
                ("y".to_owned(), Value::Float(2.0)),
                ("z".to_owned(), Value::Float(3.0)),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing struct untagged enum variant"
        );

        Ok(())
    }

    #[test]
    fn test_to_value_tuple_enum() -> TestResult {
        let test = TestTupleExternalEnum {
            a: TupleExternalEnum::Val2(1.0, 2.0, 3.0),
        };

        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("type".to_owned(), Value::Enum(1, "Val2".to_owned())),
                (
                    "value".to_owned(),
                    Value::Array(vec![
                        Value::Union(1, Box::new(Value::Float(1.0))),
                        Value::Union(1, Box::new(Value::Float(2.0))),
                        Value::Union(1, Box::new(Value::Float(3.0))),
                    ]),
                ),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing tuple external enum"
        );

        let test = TestTupleAdjacentEnum {
            a: TupleAdjacentEnum::Val1(1.0, 2.0),
        };

        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Record(vec![
                ("t".to_owned(), Value::String("Val1".to_owned())),
                (
                    "v".to_owned(),
                    Value::Array(vec![Value::Float(1.0), Value::Float(2.0)]),
                ),
            ]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing tuple adjacent enum"
        );

        let test = TestTupleUntaggedEnum {
            a: TupleUntaggedEnum::Val1(1.0, 2.0),
        };

        let expected = Value::Record(vec![(
            "a".to_owned(),
            Value::Array(vec![Value::Float(1.0), Value::Float(2.0)]),
        )]);

        assert_eq!(
            to_value(test)?,
            expected,
            "error serializing tuple untagged enum"
        );

        Ok(())
    }

    #[test]
    fn avro_3747_human_readable_false() {
        use serde::ser::Serializer as SerdeSerializer;

        crate::util::SERDE_HUMAN_READABLE.store(false, Ordering::Release);

        let ser = &mut Serializer {};

        assert_eq!(ser.is_human_readable(), false);
    }

    #[test]
    fn avro_3747_human_readable_true() {
        use serde::ser::Serializer as SerdeSerializer;

        crate::util::SERDE_HUMAN_READABLE.store(true, Ordering::Release);

        let ser = &mut Serializer {};

        assert!(ser.is_human_readable());
    }
}