zerialize 0.0.1

Zero-copy serialization
Documentation
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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
use zerialize::{Error, List, OwnedList, Writer, decode, encode, encode_in, zerializable};

mod location {
    use zerialize::zerializable;

    #[zerializable(derive(Debug, PartialEq))]
    pub trait Address {
        #[n(0)]
        fn city(&self) -> &str;

        #[n(1)]
        fn zip(&self) -> u32;
    }

    #[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
    pub struct OwnedAddress {
        pub city: String,
        pub zip: u32,
    }

    impl Address for OwnedAddress {
        fn city(&self) -> &str {
            &self.city
        }

        fn zip(&self) -> u32 {
            self.zip
        }
    }
}

// A nested schema is named by its trait, so nothing generated has to be in
// scope for `Person` to refer to `Address`.
use location::{Address, OwnedAddress};

#[zerializable(derive(Debug, PartialEq))]
trait Person {
    #[n(0)]
    fn name(&self) -> &str;

    #[n(1)]
    fn children(&self) -> impl List<Item = impl Person + '_> + '_
    where
        Self: Sized;

    #[n(2)]
    fn address(&self) -> impl Address + '_
    where
        Self: Sized;
}

#[derive(Debug)]
struct OwnedPerson {
    name: String,
    children: OwnedList<OwnedPerson>,
    address: OwnedAddress,
}

impl OwnedPerson {
    fn new(name: &str, children: Vec<OwnedPerson>) -> Self {
        Self {
            name: name.to_string(),
            children: children.into(),
            address: OwnedAddress {
                city: "Berkeley".to_string(),
                zip: 94704,
            },
        }
    }
}

impl Person for OwnedPerson {
    fn name(&self) -> &str {
        &self.name
    }

    fn children(&self) -> impl List<Item = impl Person + '_> + '_
    where
        Self: Sized,
    {
        &self.children
    }

    fn address(&self) -> impl Address + '_
    where
        Self: Sized,
    {
        &self.address
    }
}

fn family() -> OwnedPerson {
    OwnedPerson::new(
        "John",
        vec![
            OwnedPerson::new("Jimmy", vec![OwnedPerson::new("Jenny", vec![])]),
            OwnedPerson::new("Jane", vec![]),
        ],
    )
}

#[test]
fn round_trip() {
    let person = family();
    let encoded = encode::<dyn Person>(&person);
    let view = decode::<dyn Person>(&encoded).unwrap();

    assert_eq!(view.name(), "John");
    assert_eq!(view.address().city(), "Berkeley");
    assert_eq!(view.address().zip(), 94704);

    let children = view.children();
    assert_eq!(children.len(), 2);
    assert_eq!(children.get(0).unwrap().name(), "Jimmy");
    let grandchildren = children.get(0).unwrap().children();
    assert_eq!(grandchildren.get(0).unwrap().name(), "Jenny");
    assert_eq!(children.get(1).unwrap().name(), "Jane");
    assert!(children.get(1).unwrap().children().is_empty());
    assert!(children.get(2).is_none());
}

#[test]
fn view_borrows_from_the_buffer() {
    let encoded = encode::<dyn Person>(&family());
    let view = decode::<dyn Person>(&encoded).unwrap();
    let buffer = encoded.as_ptr() as usize..encoded.as_ptr() as usize + encoded.len();

    // Names are pointers into `encoded` rather than copies of it, at every
    // level of the tree: decoding a list does not materialize its elements.
    assert!(buffer.contains(&(view.name().as_ptr() as usize)));
    let child = view.children().get(0).unwrap();
    let grandchild = child.children().get(0).unwrap();
    assert!(buffer.contains(&(grandchild.name().as_ptr() as usize)));
}

#[test]
fn list_elements_are_decoded_on_access() {
    let encoded = encode::<dyn Person>(&family());
    let view = decode::<dyn Person>(&encoded).unwrap();

    let children = view.children();
    assert_eq!(children.iter().count(), 2);
    assert_eq!(
        children
            .iter()
            .map(|child| child.name())
            .collect::<Vec<_>>(),
        ["Jimmy", "Jane"]
    );
}

#[test]
fn view_compares_equal_to_the_source() {
    let person = family();
    let encoded = encode::<dyn Person>(&person);
    let view = decode::<dyn Person>(&encoded).unwrap();

    assert_eq!(view, person);
    // The source's children are opaque `impl Person`, so they are only
    // comparable, not printable, which is what assert_eq! would need.
    let children = person.children();
    assert!(view.children().get(0).unwrap() == children.get(0).unwrap());
    assert_ne!(view, OwnedPerson::new("Jack", vec![]));
    // Views are Debug, which is what makes the assertions above printable.
    assert!(format!("{view:?}").contains("Jenny"));
}

#[test]
fn view_re_encodes_identically() {
    let encoded = encode::<dyn Person>(&family());
    let view = decode::<dyn Person>(&encoded).unwrap();

    // A view implements the schema trait, so it is itself an encodable source.
    assert_eq!(encode::<dyn Person>(&view), encoded);
}

#[test]
fn encoding_into_a_buffer_appends_to_it() {
    let person = family();
    let mut buffer = vec![0xff; 3];
    let first = encode_in::<dyn Person>(&person, &mut buffer);
    let second = encode_in::<dyn Person>(&OwnedPerson::new("Jack", vec![]), &mut buffer);

    // What the buffer already held is untouched, and a message encodes the
    // same wherever it lands: offsets are relative to their own frame.
    assert_eq!(&buffer[..3], [0xff; 3]);
    assert_eq!(first, 3..second.start);
    assert_eq!(&buffer[first.clone()], encode::<dyn Person>(&person));

    assert_eq!(
        decode::<dyn Person>(&buffer[first.clone()]).unwrap(),
        person
    );
    assert_eq!(
        decode::<dyn Person>(&buffer[second]).unwrap().name(),
        "Jack"
    );
    // A message is decoded from exactly its own bytes, which is what the
    // returned range is for: the bytes of the one beside it are trailing.
    assert_eq!(
        decode::<dyn Person>(&buffer[first.start..]).unwrap_err(),
        Error::TrailingBytes
    );
}

#[test]
fn a_buffer_may_be_cleared_and_reused() {
    let person = family();
    let mut buffer = Vec::new();
    encode_in::<dyn Person>(&person, &mut buffer);

    let capacity = buffer.capacity();
    buffer.clear();
    let range = encode_in::<dyn Person>(&person, &mut buffer);

    // Reusing the allocation is the point: the same message encodes to the
    // same bytes without asking for more room.
    assert_eq!(buffer.capacity(), capacity);
    assert_eq!(range, 0..buffer.len());
    assert_eq!(decode::<dyn Person>(&buffer).unwrap(), person);
}

#[zerializable(derive(Debug, PartialEq))]
trait Primitives {
    #[n(0)]
    fn flag(&self) -> bool;

    #[n(1)]
    fn small(&self) -> u8;

    #[n(2)]
    fn signed(&self) -> i64;

    #[n(3)]
    fn ratio(&self) -> f64;

    #[n(4)]
    fn blob(&self) -> &[u8];
}

#[derive(Debug)]
struct OwnedPrimitives;

impl Primitives for OwnedPrimitives {
    fn flag(&self) -> bool {
        true
    }

    fn small(&self) -> u8 {
        u8::MAX
    }

    fn signed(&self) -> i64 {
        i64::MIN
    }

    fn ratio(&self) -> f64 {
        -0.5
    }

    fn blob(&self) -> &[u8] {
        &[0, 1, 2, 255]
    }
}

#[test]
fn primitives_round_trip() {
    let encoded = encode::<dyn Primitives>(&OwnedPrimitives);
    let view = decode::<dyn Primitives>(&encoded).unwrap();

    assert!(view.flag());
    assert_eq!(view.small(), u8::MAX);
    assert_eq!(view.signed(), i64::MIN);
    assert_eq!(view.ratio(), -0.5);
    assert_eq!(view.blob(), &[0, 1, 2, 255]);
    assert_eq!(view, OwnedPrimitives);
}

// Values are `Copy` types a schema holds by value. They are named outright,
// rather than as `impl Trait`, and nothing generated for them has to be in
// scope where the schema that holds them is.
mod cards {
    use zerialize::Zerializable;

    #[derive(Zerializable, Copy, Clone, Debug, PartialEq)]
    pub enum Suit {
        #[variant(0)]
        Clubs,
        #[variant(1)]
        Diamonds,
        #[variant(2)]
        Hearts,
        #[variant(9)]
        Spades,
    }

    #[derive(Zerializable, Copy, Clone, Debug, PartialEq)]
    pub struct Card {
        #[n(0)]
        pub rank: u8,
        #[n(1)]
        pub suit: Suit,
    }

    #[derive(Zerializable, Copy, Clone, Debug, PartialEq)]
    pub struct Play {
        // A slot is the identity of a field, so a value may declare them out of
        // order and leave gaps in them, exactly as a schema's methods may.
        #[n(3)]
        pub revealed: bool,
        #[n(0)]
        pub card: Card,
        #[n(1)]
        pub odds: f32,
    }
}

use cards::{Card, Play, Suit};

#[zerializable(derive(Debug, PartialEq))]
trait Hand {
    #[n(0)]
    fn player(&self) -> &str;

    #[n(1)]
    fn play(&self) -> Play;

    #[n(2)]
    fn trump(&self) -> cards::Suit;
}

#[derive(Debug)]
struct OwnedHand {
    player: String,
    play: Play,
}

impl Hand for OwnedHand {
    fn player(&self) -> &str {
        &self.player
    }

    fn play(&self) -> Play {
        self.play
    }

    fn trump(&self) -> Suit {
        self.play.card.suit
    }
}

fn hand() -> OwnedHand {
    OwnedHand {
        player: "Ada".to_string(),
        play: Play {
            revealed: true,
            card: Card {
                rank: 12,
                suit: Suit::Spades,
            },
            odds: 0.25,
        },
    }
}

#[test]
fn values_round_trip() {
    let hand = hand();
    let encoded = encode::<dyn Hand>(&hand);
    let view = decode::<dyn Hand>(&encoded).unwrap();

    // A value decodes back into itself, so it is the same type on both sides of
    // the wire rather than a view of the buffer.
    assert_eq!(view.play(), hand.play);
    assert_eq!(view.play().card.suit, Suit::Spades);
    assert_eq!(view.trump(), Suit::Spades);
    assert_eq!(view, hand);
    assert!(format!("{view:?}").contains("Spades"));
    assert_eq!(encode::<dyn Hand>(&view), encoded);
}

#[test]
fn a_value_outlives_the_buffer_it_was_read_from() {
    // Nothing a value holds borrows, which is what lets it escape the buffer
    // the view that produced it is a handle over.
    let play = {
        let encoded = encode::<dyn Hand>(&hand());
        decode::<dyn Hand>(&encoded).unwrap().play()
    };

    assert_eq!(play, hand().play);
}

#[test]
fn a_value_does_not_widen_the_view_that_holds_it() {
    let encoded = encode::<dyn Hand>(&hand());
    let view = decode::<dyn Hand>(&encoded).unwrap();

    // Values are read out of the buffer on access like every other field, so a
    // view of them is still one slice wide.
    assert_eq!(size_of_val(&view), size_of::<&[u8]>());
}

#[zerializable(derive(Debug, PartialEq))]
trait Trumps {
    #[n(0)]
    fn value(&self) -> Suit;
}

#[zerializable(derive(Debug, PartialEq))]
trait Numbered {
    #[n(0)]
    fn value(&self) -> u8;
}

#[test]
fn a_value_enum_costs_what_its_number_costs() {
    struct Trumped;
    impl Trumps for Trumped {
        fn value(&self) -> Suit {
            Suit::Hearts
        }
    }

    struct Counted;
    impl Numbered for Counted {
        fn value(&self) -> u8 {
            2
        }
    }

    // A variant number is all a unit variant carries, so an enum is written as
    // that number rather than as a message of its own. The number is written
    // as a variable width integer, so a small one costs a single byte.
    assert_eq!(
        encode::<dyn Trumps>(&Trumped),
        encode::<dyn Numbered>(&Counted)
    );
}

#[test]
fn corrupt_values_never_panic() {
    let encoded = encode::<dyn Hand>(&hand());
    for index in 0..encoded.len() {
        for bit in [0x01, 0x40, 0x80] {
            let mut corrupted = encoded.clone();
            corrupted[index] ^= bit;
            if let Ok(view) = decode::<dyn Hand>(&corrupted) {
                let _ = view.play();
                let _ = view.trump();
            }
        }
    }
}

/// Value evolution: `after` adds a field to a value struct, which an older
/// reader skips, and a variant to a value enum, which it cannot.
mod before {
    use zerialize::{Zerializable, zerializable};

    #[derive(Zerializable, Copy, Clone, Debug, PartialEq)]
    pub enum Color {
        #[variant(0)]
        Red,
    }

    #[derive(Zerializable, Copy, Clone, Debug, PartialEq)]
    pub struct Pixel {
        #[n(0)]
        pub color: Color,
    }

    #[zerializable(derive(Debug, PartialEq))]
    pub trait Image {
        #[n(0)]
        fn pixel(&self) -> Pixel;
    }

    pub struct OwnedImage(pub Pixel);

    impl Image for OwnedImage {
        fn pixel(&self) -> Pixel {
            self.0
        }
    }
}

mod after {
    use zerialize::{Zerializable, zerializable};

    #[derive(Zerializable, Copy, Clone, Debug, PartialEq)]
    pub enum Color {
        #[variant(0)]
        Red,
        #[variant(1)]
        Blue,
    }

    #[derive(Zerializable, Copy, Clone, Debug, PartialEq)]
    pub struct Pixel {
        #[n(0)]
        pub color: Color,
        #[n(1)]
        pub alpha: u8,
    }

    #[zerializable(derive(Debug, PartialEq))]
    pub trait Image {
        #[n(0)]
        fn pixel(&self) -> Pixel;
    }

    pub struct OwnedImage(pub Pixel);

    impl Image for OwnedImage {
        fn pixel(&self) -> Pixel {
            self.0
        }
    }
}

#[test]
fn unknown_value_slots_are_skipped() {
    let pixel = after::Pixel {
        color: after::Color::Red,
        alpha: 128,
    };
    let encoded = encode::<dyn after::Image>(&after::OwnedImage(pixel));

    // `alpha` is a slot the older value does not know, so it is never read.
    let view = decode::<dyn before::Image>(&encoded).unwrap();
    assert_eq!(
        view.pixel(),
        before::Pixel {
            color: before::Color::Red
        }
    );
}

#[test]
fn missing_value_slots_are_rejected() {
    let pixel = before::Pixel {
        color: before::Color::Red,
    };
    let encoded = encode::<dyn before::Image>(&before::OwnedImage(pixel));

    assert_eq!(
        decode::<dyn after::Image>(&encoded).unwrap_err(),
        Error::MissingField
    );
}

#[test]
fn unknown_variants_are_rejected() {
    // Unlike a slot, which a reader skips by never asking for it, a variant it
    // does not know is data it cannot represent.
    let pixel = after::Pixel {
        color: after::Color::Blue,
        alpha: 0,
    };
    let encoded = encode::<dyn after::Image>(&after::OwnedImage(pixel));
    assert_eq!(
        decode::<dyn before::Image>(&encoded).unwrap_err(),
        Error::UnknownVariant
    );

    // The variant it does know still decodes, out of the same slot.
    let pixel = after::Pixel {
        color: after::Color::Red,
        alpha: 0,
    };
    let encoded = encode::<dyn after::Image>(&after::OwnedImage(pixel));
    assert!(decode::<dyn before::Image>(&encoded).is_ok());
}

/// Schema evolution: `v2` adds a slot that `v1` readers do not know about.
mod v1 {
    use zerialize::zerializable;

    #[zerializable(derive(Debug, PartialEq))]
    pub trait Record {
        #[n(0)]
        fn id(&self) -> u32;
    }
}

mod v2 {
    use zerialize::zerializable;

    #[zerializable(derive(Debug, PartialEq))]
    pub trait Record {
        #[n(0)]
        fn id(&self) -> u32;

        #[n(7)]
        fn label(&self) -> &str;
    }

    pub struct OwnedRecord;

    impl Record for OwnedRecord {
        fn id(&self) -> u32 {
            7
        }

        fn label(&self) -> &str {
            "added later"
        }
    }
}

#[test]
fn unknown_slots_are_skipped() {
    let encoded = encode::<dyn v2::Record>(&v2::OwnedRecord);
    let view = decode::<dyn v1::Record>(&encoded).unwrap();

    assert_eq!(view.id(), 7);
}

#[test]
fn missing_slots_are_rejected() {
    struct OldRecord;
    impl v1::Record for OldRecord {
        fn id(&self) -> u32 {
            7
        }
    }

    let encoded = encode::<dyn v1::Record>(&OldRecord);
    assert_eq!(
        decode::<dyn v2::Record>(&encoded).unwrap_err(),
        Error::MissingField
    );
}

#[test]
fn truncated_input_is_rejected() {
    let encoded = encode::<dyn Person>(&family());
    for length in 0..encoded.len() {
        assert!(decode::<dyn Person>(&encoded[..length]).is_err());
    }
}

#[test]
fn trailing_bytes_are_rejected() {
    let mut encoded = encode::<dyn Person>(&family());
    encoded.push(0);
    assert_eq!(
        decode::<dyn Person>(&encoded).unwrap_err(),
        Error::TrailingBytes
    );
}

#[test]
fn invalid_utf8_is_rejected() {
    let mut encoded = encode::<dyn Person>(&OwnedPerson::new("John", vec![]));
    let start = encoded
        .windows(4)
        .position(|window| window == b"John")
        .expect("the name is stored verbatim");
    encoded[start] = 0xff;

    assert_eq!(
        decode::<dyn Person>(&encoded).unwrap_err(),
        Error::InvalidUtf8
    );
}

#[test]
fn a_length_that_cannot_be_added_to_is_rejected() {
    // A length word is a claim about the buffer rather than a length: the
    // largest one there is names bytes past the end of every buffer, so it has
    // to be rejected before it is added to an offset.
    let mut encoded = Vec::new();
    let mut writer = Writer::new(&mut encoded);
    let frame = writer.begin_frame(1);
    writer.begin_entry(&frame, 0);
    writer.write_u64(u64::MAX);
    writer.end_frame(frame);

    assert_eq!(
        decode::<dyn Person>(&encoded).unwrap_err(),
        Error::UnexpectedEof
    );
}

#[test]
fn deep_nesting_is_rejected() {
    fn chain(depth: usize) -> OwnedPerson {
        let mut person = OwnedPerson::new("leaf", vec![]);
        for _ in 0..depth {
            person = OwnedPerson::new("node", vec![person]);
        }
        person
    }

    let shallow = encode::<dyn Person>(&chain(32));
    assert!(decode::<dyn Person>(&shallow).is_ok());

    let deep = encode::<dyn Person>(&chain(200));
    assert_eq!(
        decode::<dyn Person>(&deep).unwrap_err(),
        Error::RecursionLimit
    );
}

#[test]
fn corrupt_input_never_panics() {
    fn walk<P: Person>(person: &P) {
        let _ = person.name();
        let _ = person.address().city();
        let children = person.children();
        for child in children.iter() {
            walk(&child);
        }
    }

    // Decoding validates the whole message, which is what lets every accessor
    // on a view, including lazily decoded list elements, be infallible.
    let encoded = encode::<dyn Person>(&family());
    for index in 0..encoded.len() {
        for bit in [0x01, 0x40, 0x80] {
            let mut corrupted = encoded.clone();
            corrupted[index] ^= bit;
            if let Ok(view) = decode::<dyn Person>(&corrupted) {
                walk(&view);
            }
        }
    }
}

#[test]
fn view_is_a_thin_handle() {
    fn assert_copy<T: Copy>(_: &T) {}

    let encoded = encode::<dyn Person>(&family());
    let view = decode::<dyn Person>(&encoded).unwrap();

    // Copy is the structural half of the claim: a view that owned any of its
    // contents, a String or a Vec of decoded children, could not be Copy.
    assert_copy(&view);

    // A view is the bytes of its message and nothing else. Fields are read out
    // of them on access, so a view is one slice wide whatever its schema holds,
    // and a nested message costs exactly what the message holding it does.
    let handle = size_of::<&[u8]>();
    assert_eq!(size_of_val(&view), handle);
    assert_eq!(size_of_val(&view.address()), handle);

    // A list is walked rather than read out once, so its handle also carries
    // what the frame's header said, read where the list was reached rather
    // than again at every element. It is a constant all the same: a list costs
    // what it costs however long it is and whatever it holds.
    let alone = encode::<dyn Person>(&OwnedPerson::new("solo", vec![]));
    let alone = decode::<dyn Person>(&alone).unwrap();
    assert_eq!(
        size_of_val(&view.children()),
        size_of_val(&alone.children())
    );
    assert!(size_of_val(&view.children()) <= 8 * handle);

    // Nor does the count of fields change it: five slots cost what three do,
    // and one scalar costs the same again.
    let encoded = encode::<dyn Primitives>(&OwnedPrimitives);
    assert_eq!(
        size_of_val(&decode::<dyn Primitives>(&encoded).unwrap()),
        handle
    );
    let encoded = encode::<dyn v2::Record>(&v2::OwnedRecord);
    assert_eq!(
        size_of_val(&decode::<dyn v1::Record>(&encoded).unwrap()),
        handle
    );
}

/// A schema declared as an enum, carrying two schemas of its own.
#[zerializable(derive(PartialEq))]
#[derive(Debug)]
enum Role<P: Person, A: Address> {
    #[variant(0)]
    Resident(#[n(0)] P),
    #[variant(1)]
    Office(#[n(0)] A, #[n(1)] u32),
    #[variant(2)]
    Vacant,
}

fn office() -> Role<OwnedPerson, OwnedAddress> {
    Role::Office(
        OwnedAddress {
            city: "Oakland".to_string(),
            zip: 94607,
        },
        12,
    )
}

#[test]
fn enum_round_trips() {
    let resident: Role<OwnedPerson, OwnedAddress> = Role::Resident(family());
    let encoded = encode::<Role<dyn Person, dyn Address>>(&resident);

    match decode::<Role<dyn Person, dyn Address>>(&encoded).unwrap() {
        Role::Resident(person) => {
            assert_eq!(person.name(), "John");
            assert_eq!(person.children().len(), 2);
        }
        _ => panic!("decoded the wrong variant"),
    }
}

#[test]
fn every_variant_carries_its_own_fields() {
    let encoded = encode::<Role<dyn Person, dyn Address>>(&office());
    match decode::<Role<dyn Person, dyn Address>>(&encoded).unwrap() {
        Role::Office(address, floor) => {
            assert_eq!(address.city(), "Oakland");
            assert_eq!(address.zip(), 94607);
            assert_eq!(floor, 12);
        }
        _ => panic!("decoded the wrong variant"),
    }

    let vacant: Role<OwnedPerson, OwnedAddress> = Role::Vacant;
    let encoded = encode::<Role<dyn Person, dyn Address>>(&vacant);
    assert!(matches!(
        decode::<Role<dyn Person, dyn Address>>(&encoded).unwrap(),
        Role::Vacant
    ));
}

#[test]
fn a_stored_enum_is_handed_out_borrowed() {
    let stored = office();

    // What an implementation stores is handed out by borrowing the messages
    // its variant carries and copying the scalars, so the two encode alike.
    let borrowed: Role<&OwnedPerson, &OwnedAddress> = stored.as_ref();
    assert_eq!(
        encode::<Role<dyn Person, dyn Address>>(&borrowed),
        encode::<Role<dyn Person, dyn Address>>(&stored)
    );

    let vacant: Role<OwnedPerson, OwnedAddress> = Role::Vacant;
    assert!(matches!(vacant.as_ref(), Role::Vacant));
}

#[test]
fn enum_payloads_borrow_from_the_buffer() {
    let resident: Role<OwnedPerson, OwnedAddress> = Role::Resident(family());
    let encoded = encode::<Role<dyn Person, dyn Address>>(&resident);
    let buffer = encoded.as_ptr() as usize..encoded.as_ptr() as usize + encoded.len();

    // Decoding an enum decides its variant, and nothing else: what the variant
    // carries is still a view of the buffer it was decoded from.
    match decode::<Role<dyn Person, dyn Address>>(&encoded).unwrap() {
        Role::Resident(person) => {
            assert!(buffer.contains(&(person.name().as_ptr() as usize)));
        }
        _ => panic!("decoded the wrong variant"),
    }
}

#[test]
fn decoded_enum_re_encodes_identically() {
    let resident: Role<OwnedPerson, OwnedAddress> = Role::Resident(family());
    let encoded = encode::<Role<dyn Person, dyn Address>>(&resident);
    let decoded = decode::<Role<dyn Person, dyn Address>>(&encoded).unwrap();

    // The decoded enum is the enum over views, and a view implements the schema
    // it was decoded as, so the whole of it is encodable again.
    assert_eq!(encode::<Role<dyn Person, dyn Address>>(&decoded), encoded);
}

#[test]
fn corrupt_enum_input_never_panics() {
    let resident: Role<OwnedPerson, OwnedAddress> = Role::Resident(family());
    for encoded in [
        encode::<Role<dyn Person, dyn Address>>(&resident),
        encode::<Role<dyn Person, dyn Address>>(&office()),
    ] {
        for index in 0..encoded.len() {
            for bit in [0x01, 0x40, 0x80] {
                let mut corrupted = encoded.clone();
                corrupted[index] ^= bit;
                // Corrupting the tag decodes one variant's fields as another's,
                // which is as validated as any other input: it may be nonsense,
                // but reading it cannot fail.
                match decode::<Role<dyn Person, dyn Address>>(&corrupted) {
                    Ok(Role::Resident(person)) => {
                        let _ = person.name();
                        for child in person.children().iter() {
                            let _ = child.name();
                        }
                    }
                    Ok(Role::Office(address, floor)) => {
                        let _ = address.city();
                        let _ = floor;
                    }
                    Ok(Role::Vacant) | Err(_) => (),
                }
            }
        }
    }
}

/// The same choice as `Role`, with the fields of each variant named rather than
/// positional. A slot is what names a field on the wire, so the two are one
/// schema; the names are how the enum reads in Rust.
#[zerializable(derive(PartialEq))]
#[derive(Debug)]
enum Tenant<P: Person, A: Address> {
    #[variant(0)]
    Resident {
        #[n(0)]
        person: P,
    },
    #[variant(1)]
    Office {
        #[n(0)]
        address: A,
        #[n(1)]
        floor: u32,
    },
    #[variant(2)]
    Vacant,
}

fn tenant_office() -> Tenant<OwnedPerson, OwnedAddress> {
    Tenant::Office {
        address: OwnedAddress {
            city: "Oakland".to_string(),
            zip: 94607,
        },
        floor: 12,
    }
}

#[test]
fn a_variant_may_name_its_fields() {
    let resident: Tenant<OwnedPerson, OwnedAddress> = Tenant::Resident { person: family() };
    let encoded = encode::<Tenant<dyn Person, dyn Address>>(&resident);

    match decode::<Tenant<dyn Person, dyn Address>>(&encoded).unwrap() {
        Tenant::Resident { person } => {
            assert_eq!(person.name(), "John");
            assert_eq!(person.children().len(), 2);
        }
        _ => panic!("decoded the wrong variant"),
    }
}

#[test]
fn naming_a_field_leaves_the_wire_alone() {
    // What names a field on the wire is its slot, so a variant that names its
    // fields and one that does not are the same message: either writes what
    // the other reads.
    let positional = encode::<Role<dyn Person, dyn Address>>(&office());
    assert_eq!(
        encode::<Tenant<dyn Person, dyn Address>>(&tenant_office()),
        positional
    );
    match decode::<Tenant<dyn Person, dyn Address>>(&positional).unwrap() {
        Tenant::Office { address, floor } => {
            assert_eq!(address.city(), "Oakland");
            assert_eq!(address.zip(), 94607);
            assert_eq!(floor, 12);
        }
        _ => panic!("decoded the wrong variant"),
    }
}

#[test]
fn a_named_variant_is_borrowed_and_compared_like_any_other() {
    let stored = tenant_office();

    let borrowed: Tenant<&OwnedPerson, &OwnedAddress> = stored.as_ref();
    let encoded = encode::<Tenant<dyn Person, dyn Address>>(&stored);
    assert_eq!(
        encode::<Tenant<dyn Person, dyn Address>>(&borrowed),
        encoded
    );

    // The comparison across instantiations: the enum over views, against the
    // enum over the implementation it was encoded from.
    assert_eq!(
        decode::<Tenant<dyn Person, dyn Address>>(&encoded).unwrap(),
        stored
    );

    let vacant: Tenant<OwnedPerson, OwnedAddress> = Tenant::Vacant;
    assert!(matches!(vacant.as_ref(), Tenant::Vacant));
}

/// A choice whose empty variants are each written a different way.
#[zerializable]
#[derive(Debug, Clone, PartialEq)]
enum Vacancy<A: Address> {
    #[variant(0)]
    Unit,
    #[variant(1)]
    Tuple(),
    #[variant(2)]
    Named {},
    #[variant(3)]
    Taken {
        #[n(0)]
        address: A,
    },
}

#[test]
fn a_variant_carrying_nothing_keeps_the_shape_it_was_written_with() {
    // `V`, `V()`, and `V {}` are three different declarations to Rust even
    // where all three carry nothing, so each is built and matched as written.
    let unit: Vacancy<OwnedAddress> = Vacancy::Unit;
    let tuple: Vacancy<OwnedAddress> = Vacancy::Tuple();
    let named: Vacancy<OwnedAddress> = Vacancy::Named {};

    let encoded = encode::<Vacancy<dyn Address>>(&unit);
    let decoded = decode::<Vacancy<dyn Address>>(&encoded).unwrap();
    assert!(matches!(decoded, Vacancy::Unit));
    let encoded = encode::<Vacancy<dyn Address>>(&tuple);
    let decoded = decode::<Vacancy<dyn Address>>(&encoded).unwrap();
    assert!(matches!(decoded, Vacancy::Tuple()));
    let encoded = encode::<Vacancy<dyn Address>>(&named);
    let decoded = decode::<Vacancy<dyn Address>>(&encoded).unwrap();
    assert!(matches!(decoded, Vacancy::Named {}));

    assert!(matches!(tuple.as_ref(), Vacancy::Tuple()));
    assert!(matches!(named.as_ref(), Vacancy::Named {}));

    // What an ordinary `derive` writes, hoisted above the attribute, over the
    // variants it rewrote.
    assert_eq!(named.clone(), named);
    assert_ne!(named, unit);
    assert!(format!("{named:?}").contains("Named"));
}

/// A schema that asks for nothing, which is what a schema costs by default.
mod plain {
    use zerialize::{Zerializable, zerializable};

    /// Neither `Debug` nor `PartialEq`, which a value is no longer required to
    /// have: only a schema asked to print or compare its fields needs them.
    #[derive(Zerializable, Copy, Clone)]
    pub struct Weight {
        #[n(0)]
        pub grams: u32,
    }

    #[zerializable]
    pub trait Note {
        #[n(0)]
        fn text(&self) -> &str;

        #[n(1)]
        fn weight(&self) -> Weight;
    }

    // A choice whose `PartialEq` is its own, which is what asking for nothing
    // leaves available.
    #[zerializable]
    #[derive(Debug, Clone, PartialEq)]
    pub enum Entry<N: Note> {
        #[variant(0)]
        Written(#[n(0)] N),
        #[variant(1)]
        Blank,
    }

    #[derive(Debug, Clone, PartialEq)]
    pub struct OwnedNote(pub &'static str);

    impl Note for OwnedNote {
        fn text(&self) -> &str {
            self.0
        }

        fn weight(&self) -> Weight {
            Weight { grams: 3 }
        }
    }
}

#[test]
fn a_schema_asks_for_only_what_it_needs() {
    use plain::{Entry, Note, OwnedNote};

    // Nothing was asked for, so nothing was generated, and the schema still
    // round trips: printing and comparing are what a schema is asked for, not
    // what it is made of.
    let entry: Entry<OwnedNote> = Entry::Written(OwnedNote("hello"));
    let encoded = encode::<Entry<dyn Note>>(&entry);
    match decode::<Entry<dyn Note>>(&encoded).unwrap() {
        Entry::Written(note) => {
            assert_eq!(note.text(), "hello");
            assert_eq!(note.weight().grams, 3);
        }
        Entry::Blank => panic!("decoded the wrong variant"),
    }

    // The enum's own `PartialEq` and `Debug`, which asking for the generic
    // comparison would have claimed.
    let blank: Entry<OwnedNote> = Entry::Blank;
    assert_eq!(blank, blank.clone());
    assert_ne!(format!("{blank:?}"), format!("{entry:?}"));
}

/// The same declaration twice, with a `#[derive]` on either side of the
/// attribute, since the two are meant to read alike.
#[zerializable(derive(PartialEq))]
#[derive(Debug, Clone, Default, Eq, Hash, PartialOrd, Ord)]
enum Tenancy<A: Address> {
    #[variant(0)]
    #[default]
    Vacant,
    #[variant(1)]
    Leased(#[n(0)] A, #[n(1)] u32),
}

#[derive(Clone, Default, Eq, Hash, PartialOrd, Ord)]
#[zerializable(derive(PartialEq))]
#[derive(Debug)]
enum Tenancy2<A: Address> {
    #[variant(0)]
    #[default]
    Vacant,
    #[variant(1)]
    Leased(#[n(0)] A, #[n(1)] u32),
}

#[test]
fn an_enum_derives_on_either_side_of_the_attribute() {
    let oakland = OwnedAddress {
        city: "Oakland".to_string(),
        zip: 94607,
    };
    let below: Tenancy<OwnedAddress> = Tenancy::Leased(oakland.clone(), 12);
    let above: Tenancy2<OwnedAddress> = Tenancy2::Leased(oakland, 12);

    // Each implementation is bounded by the enum's parameters, as a `derive`
    // writes it, so it holds of the enum over any payload that has it.
    assert_eq!(below.clone(), below);
    assert_eq!(above.clone(), above);
    assert_eq!(Tenancy::<OwnedAddress>::default(), Tenancy::Vacant);
    assert_eq!(Tenancy2::<OwnedAddress>::default(), Tenancy2::Vacant);
    assert!(below > Tenancy::Vacant);
    assert!(above > Tenancy2::Vacant);
    let mut leases = std::collections::HashSet::new();
    assert!(leases.insert(below.clone()));
    assert!(!leases.insert(below.clone()));

    // What the attribute generates is untouched by any of it.
    let encoded = encode::<Tenancy<dyn Address>>(&below);
    assert_eq!(decode::<Tenancy<dyn Address>>(&encoded).unwrap(), below);
    let encoded = encode::<Tenancy2<dyn Address>>(&above);
    assert_eq!(decode::<Tenancy2<dyn Address>>(&encoded).unwrap(), above);
}

/// A message carrying enums: one on its own, and one per element of a list.
#[zerializable(derive(Debug, PartialEq))]
trait Building {
    #[n(0)]
    fn owner(&self) -> Role<impl Person + '_, impl Address + '_>
    where
        Self: Sized;

    #[n(1)]
    fn tenants(&self) -> impl List<Item = Role<impl Person + '_, impl Address + '_>> + '_
    where
        Self: Sized;
}

#[derive(Debug)]
struct OwnedBuilding {
    owner: OwnedPerson,
    tenants: OwnedList<OwnedAddress>,
}

impl Building for OwnedBuilding {
    fn owner(&self) -> Role<impl Person + '_, impl Address + '_>
    where
        Self: Sized,
    {
        // Borrowed out of self, exactly as a nested message is.
        Role::<&OwnedPerson, &OwnedAddress>::Resident(&self.owner)
    }

    fn tenants(&self) -> impl List<Item = Role<impl Person + '_, impl Address + '_>> + '_
    where
        Self: Sized,
    {
        Offices(&self.tenants)
    }
}

/// A list whose elements are built as they are asked for, which is what lets an
/// implementation hand out enums it does not store.
struct Offices<'a>(&'a OwnedList<OwnedAddress>);

impl<'a> List for Offices<'a> {
    type Item = Role<&'a OwnedPerson, &'a OwnedAddress>;

    fn len(&self) -> usize {
        self.0.len()
    }

    fn get(&self, index: usize) -> Option<Self::Item> {
        Some(Role::Office(self.0.as_slice().get(index)?, index as u32))
    }
}

fn building() -> OwnedBuilding {
    OwnedBuilding {
        owner: family(),
        tenants: vec![
            OwnedAddress {
                city: "Oakland".to_string(),
                zip: 94607,
            },
            OwnedAddress {
                city: "Alameda".to_string(),
                zip: 94501,
            },
        ]
        .into(),
    }
}

#[test]
fn a_message_carries_an_enum() {
    let encoded = encode::<dyn Building>(&building());
    let view = decode::<dyn Building>(&encoded).unwrap();

    match view.owner() {
        Role::Resident(person) => assert_eq!(person.name(), "John"),
        _ => panic!("decoded the wrong variant"),
    }

    let tenants = view.tenants();
    assert_eq!(tenants.len(), 2);
    match tenants.get(1).unwrap() {
        Role::Office(address, floor) => {
            assert_eq!(address.city(), "Alameda");
            assert_eq!(floor, 1);
        }
        _ => panic!("decoded the wrong variant"),
    }
}

#[test]
fn corrupt_input_carrying_an_enum_never_panics() {
    // Reading a carried enum through a view is infallible, which holds only
    // because decoding the message decided every enum it holds, including the
    // ones its lists hold.
    let encoded = encode::<dyn Building>(&building());
    for index in 0..encoded.len() {
        for bit in [0x01, 0x40, 0x80] {
            let mut corrupted = encoded.clone();
            corrupted[index] ^= bit;
            let Ok(view) = decode::<dyn Building>(&corrupted) else {
                continue;
            };
            let _ = view.owner();
            for tenant in view.tenants().iter() {
                let _ = tenant;
            }
        }
    }
}

#[test]
fn a_carried_enum_is_part_of_its_message() {
    let building = building();
    let encoded = encode::<dyn Building>(&building);
    let view = decode::<dyn Building>(&encoded).unwrap();

    // A view compares against the source and prints, both of which reach
    // through the enum it carries.
    assert_eq!(view, building);
    assert!(format!("{view:?}").contains("Resident"));

    // And it re-encodes as itself, so a carried enum round trips both ways.
    assert_eq!(encode::<dyn Building>(&view), encoded);

    // The enum is decided when it is read, but what it carries is still a view
    // of the buffer.
    let buffer = encoded.as_ptr() as usize..encoded.as_ptr() as usize + encoded.len();
    match view.owner() {
        Role::Resident(person) => {
            assert!(buffer.contains(&(person.name().as_ptr() as usize)));
        }
        _ => panic!("decoded the wrong variant"),
    }
}

/// Choice evolution: `command_v2` adds a field to a variant, and a variant of
/// its own. A choice carrying no schemas is its own name and its own view.
mod command_v1 {
    use zerialize::zerializable;

    #[zerializable(derive(PartialEq))]
    #[derive(Debug)]
    pub enum Command {
        #[variant(0)]
        Wait(#[n(0)] u32),
    }
}

mod command_v2 {
    use zerialize::zerializable;

    #[zerializable(derive(PartialEq))]
    #[derive(Debug)]
    pub enum Command {
        #[variant(0)]
        Wait(#[n(0)] u32, #[n(1)] bool),
        #[variant(1)]
        Stop,
    }
}

#[test]
fn unknown_fields_of_a_variant_are_skipped() {
    let encoded = encode::<command_v2::Command>(&command_v2::Command::Wait(3, true));
    assert_eq!(
        decode::<command_v1::Command>(&encoded).unwrap(),
        command_v1::Command::Wait(3)
    );
}

#[test]
fn missing_fields_of_a_variant_are_rejected() {
    let encoded = encode::<command_v1::Command>(&command_v1::Command::Wait(3));
    assert_eq!(
        decode::<command_v2::Command>(&encoded).unwrap_err(),
        Error::MissingField
    );
}

#[test]
fn an_unknown_variant_of_a_choice_is_rejected() {
    // A reader has nothing to decode a variant it does not know as, which is
    // what separates adding a variant from adding a field.
    let encoded = encode::<command_v2::Command>(&command_v2::Command::Stop);
    assert_eq!(
        decode::<command_v1::Command>(&encoded).unwrap_err(),
        Error::UnknownVariant
    );
}

#[test]
fn view_size_does_not_depend_on_the_data() {
    fn wide(children: usize) -> OwnedPerson {
        OwnedPerson::new(
            "root",
            (0..children)
                .map(|_| OwnedPerson::new("child", vec![]))
                .collect(),
        )
    }

    let small = encode::<dyn Person>(&wide(1));
    let large = encode::<dyn Person>(&wide(10_000));
    assert!(large.len() > 100 * small.len());

    // Decoding is a handle over the buffer, so a view of a megabyte of people
    // is the same size as a view of one, and so is any child reached from it.
    let small_view = decode::<dyn Person>(&small).unwrap();
    let large_view = decode::<dyn Person>(&large).unwrap();
    assert_eq!(size_of_val(&small_view), size_of_val(&large_view));
    assert_eq!(
        size_of_val(&large_view.children().get(9_999).unwrap()),
        size_of_val(&large_view)
    );
}