postbag 1.0.0

💼 Postbag is a compact binary serde codec for Rust with built-in support for schema evolution. Fields and enum variants can be added, removed and reordered while old and new programs continue to exchange data.
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
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::fmt::Debug;

use postbag::{
    cfg::{Cfg, Full, Slim, Version},
    deserialize, serialize,
};

/// Transform from one type to another via serialization followed by deserialization.
#[track_caller]
pub fn transform<T, R, const WITH_IDENTS: bool>(value: &T, cfg: Cfg<WITH_IDENTS>) -> R
where
    T: Serialize + DeserializeOwned + Debug + Eq,
    R: DeserializeOwned,
{
    let mut serialized = Vec::new();
    serialize(cfg, &mut serialized, &value).expect("serialization failed");
    println!("{serialized:02x?}");
    dbg!(serialized.len());

    let deserialized: T = deserialize(cfg, serialized.as_slice()).expect("deserialization failed");

    assert_eq!(*value, deserialized, "deserialized value does not match original value");

    deserialize(cfg, serialized.as_slice()).expect("deserialization to transformed type failed")
}

#[test]
fn changed_struct_fields() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        f1: u32,
        f2: u32,
        f3: u32,
    }

    #[derive(Serialize, Deserialize)]
    struct B {
        f2: u32,
        #[serde(default = "f4_default")]
        f4: u32,
    }

    const fn f4_default() -> u32 {
        4
    }

    let a = A { f1: 1, f2: 2, f3: 3 };

    let b: B = transform(&a, Full::new());

    assert_eq!(b.f2, a.f2);
    assert_eq!(b.f4, f4_default());
}

#[test]
fn added_struct_fields() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        f1: u32,
        f2: u32,
        f3: u32,
    }

    #[derive(Serialize, Deserialize)]
    struct B {
        f1: u32,
        f2: u32,
        f3: u32,
        #[serde(default = "f4_default")]
        f4: u32,
    }

    const fn f4_default() -> u32 {
        4
    }

    let a = A { f1: 1, f2: 2, f3: 3 };

    let b: B = transform(&a, Full::new());
    assert_eq!(b.f1, a.f1);
    assert_eq!(b.f2, a.f2);
    assert_eq!(b.f3, a.f3);
    assert_eq!(b.f4, f4_default());

    let b: B = transform(&a, Slim::new());
    assert_eq!(b.f1, a.f1);
    assert_eq!(b.f2, a.f2);
    assert_eq!(b.f3, a.f3);
    assert_eq!(b.f4, f4_default());
}

#[test]
fn changed_struct_variant_fields() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum A {
        V1,
        V2 { f1: u32, f2: u32, f3: u32 },
        V3,
    }

    #[derive(Serialize, Deserialize)]
    enum B {
        V1a,
        V3b,
        V2 {
            f2: u32,
            #[serde(default = "f4_default")]
            f4: u32,
        },
    }

    const fn f4_default() -> u32 {
        4
    }

    let a_f2 = 2;
    let a = A::V2 { f1: 1, f2: a_f2, f3: 3 };

    let b: B = transform(&a, Full::new());

    let B::V2 { f2, f4 } = b else { panic!("wrong variant") };
    assert_eq!(f2, a_f2);
    assert_eq!(f4, f4_default());
}

#[test]
fn added_struct_variant_fields() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum A {
        V1,
        V2 { f1: u32, f2: u32, f3: u32 },
        V3,
    }

    #[derive(Serialize, Deserialize)]
    enum B {
        V1a,
        V2 {
            f1: u32,
            f2: u32,
            f3: u32,
            #[serde(default = "f4_default")]
            f4: u32,
        },
    }

    const fn f4_default() -> u32 {
        4
    }

    let a_f1 = 1;
    let a_f2 = 2;
    let a_f3 = 3;
    let a = A::V2 { f1: a_f1, f2: a_f2, f3: a_f3 };

    let b: B = transform(&a, Full::new());
    let B::V2 { f1, f2, f3, f4 } = b else { panic!("wrong variant") };
    assert_eq!(f1, a_f1);
    assert_eq!(f2, a_f2);
    assert_eq!(f3, a_f3);
    assert_eq!(f4, f4_default());

    let b: B = transform(&a, Slim::new());
    let B::V2 { f1, f2, f3, f4 } = b else { panic!("wrong variant") };
    assert_eq!(f1, a_f1);
    assert_eq!(f2, a_f2);
    assert_eq!(f3, a_f3);
    assert_eq!(f4, f4_default());
}

#[test]
fn removed_struct_fields_nested_struct() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        f1: u32,
        f2: u32,
        f3: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct XA {
        a: A,
        x: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct B {
        f1: u32,
        f2: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct XB {
        a: B,
        x: u32,
    }

    let xa = XA { a: A { f1: 1, f2: 2, f3: 3 }, x: 99 };

    let xb: XB = transform(&xa, Full::new());
    assert_eq!(xb.a.f1, xa.a.f1);
    assert_eq!(xb.a.f2, xa.a.f2);
    assert_eq!(xb.x, xa.x);

    let xb: XB = transform(&xa, Slim::new());
    assert_eq!(xb.a.f1, xa.a.f1);
    assert_eq!(xb.a.f2, xa.a.f2);
    assert_eq!(xb.x, xa.x);
}

#[test]
fn removed_struct_fields_nested_tuple() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        f1: u32,
        f2: u32,
        f3: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct B {
        f1: u32,
        f2: u32,
    }

    let xa = (A { f1: 1, f2: 2, f3: 3 }, 99);

    let xb: (B, u32) = transform(&xa, Full::new());
    assert_eq!(xb.0.f1, xa.0.f1);
    assert_eq!(xb.0.f2, xa.0.f2);
    assert_eq!(xb.1, xa.1);

    let xb: (B, u32) = transform(&xa, Slim::new());
    assert_eq!(xb.0.f1, xa.0.f1);
    assert_eq!(xb.0.f2, xa.0.f2);
    assert_eq!(xb.1, xa.1);
}

#[test]
fn added_enum_variants_slim_encoding() {
    // Original enum with 3 variants
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum Original {
        Variant1,
        Variant2(u32),
        Variant3 { value: String },
    }

    // Extended enum with additional variants at the end
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum Extended {
        Variant1,
        Variant2(u32),
        Variant3 {
            value: String,
        },
        Variant4,
        Variant5(bool),
        #[serde(other)]
        Unknown,
    }

    // Even more extended enum for backward compatibility testing
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum MoreExtended {
        Variant1,
        Variant2(u32),
        Variant3 {
            value: String,
        },
        Variant4,
        Variant5(bool),
        Variant6 {
            x: i32,
            y: i32,
        },
        #[serde(other)]
        Unknown,
    }

    // Test forward compatibility: Original -> Extended
    let original_v1 = Original::Variant1;
    let extended_v1: Extended = transform(&original_v1, Slim::new());
    assert_eq!(extended_v1, Extended::Variant1);

    let original_v2 = Original::Variant2(42);
    let extended_v2: Extended = transform(&original_v2, Slim::new());
    assert_eq!(extended_v2, Extended::Variant2(42));

    let original_v3 = Original::Variant3 { value: "test".to_string() };
    let extended_v3: Extended = transform(&original_v3, Slim::new());
    assert_eq!(extended_v3, Extended::Variant3 { value: "test".to_string() });

    // Test backward compatibility: Extended -> Original (with #[serde(other)])
    let extended_v4 = Extended::Variant4;
    let mut serialized = Vec::new();
    serialize(Slim::new(), &mut serialized, &extended_v4).expect("serialization failed");

    // This should deserialize to Unknown variant when using Original enum with #[serde(other)]
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum OriginalWithOther {
        Variant1,
        Variant2(u32),
        Variant3 {
            value: String,
        },
        #[serde(other)]
        Unknown,
    }

    let deserialized: OriginalWithOther =
        deserialize(Slim::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, OriginalWithOther::Unknown);

    let extended_v5 = Extended::Variant5(true);
    let mut serialized = Vec::new();
    serialize(Slim::new(), &mut serialized, &extended_v5).expect("serialization failed");
    let deserialized: OriginalWithOther =
        deserialize(Slim::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, OriginalWithOther::Unknown);

    // Test compatibility with even more extended version
    let more_extended_v6 = MoreExtended::Variant6 { x: 10, y: 20 };
    let mut serialized = Vec::new();
    serialize(Slim::new(), &mut serialized, &more_extended_v6).expect("serialization failed");

    // Should deserialize to Unknown in Extended enum
    let deserialized: Extended = deserialize(Slim::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, Extended::Unknown);

    // Should also deserialize to Unknown in OriginalWithOther enum
    let deserialized: OriginalWithOther =
        deserialize(Slim::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, OriginalWithOther::Unknown);

    // Test that existing variants still work across all versions
    let more_extended_v1 = MoreExtended::Variant1;
    let extended_v1: Extended = transform(&more_extended_v1, Slim::new());
    assert_eq!(extended_v1, Extended::Variant1);

    let original_v1: OriginalWithOther = transform(&more_extended_v1, Slim::new());
    assert_eq!(original_v1, OriginalWithOther::Variant1);
}

#[test]
fn added_enum_variants_full_encoding() {
    // Original enum with 3 variants
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum Original {
        Variant1,
        Variant2(u32),
        Variant3 { value: String },
    }

    // Extended enum with additional variants at the end
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum Extended {
        Variant1,
        Variant2(u32),
        Variant3 {
            value: String,
        },
        Variant4,
        Variant5(bool),
        #[serde(other)]
        Unknown,
    }

    // Even more extended enum for backward compatibility testing
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum MoreExtended {
        Variant1,
        Variant2(u32),
        Variant3 {
            value: String,
        },
        Variant4,
        Variant5(bool),
        Variant6 {
            x: i32,
            y: i32,
        },
        #[serde(other)]
        Unknown,
    }

    // Test forward compatibility: Original -> Extended
    let original_v1 = Original::Variant1;
    let extended_v1: Extended = transform(&original_v1, Full::new());
    assert_eq!(extended_v1, Extended::Variant1);

    let original_v2 = Original::Variant2(42);
    let extended_v2: Extended = transform(&original_v2, Full::new());
    assert_eq!(extended_v2, Extended::Variant2(42));

    let original_v3 = Original::Variant3 { value: "test".to_string() };
    let extended_v3: Extended = transform(&original_v3, Full::new());
    assert_eq!(extended_v3, Extended::Variant3 { value: "test".to_string() });

    // Test backward compatibility: Extended -> Original (with #[serde(other)])
    let extended_v4 = Extended::Variant4;
    let mut serialized = Vec::new();
    serialize(Full::new(), &mut serialized, &extended_v4).expect("serialization failed");

    // This should deserialize to Unknown variant when using Original enum with #[serde(other)]
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum OriginalWithOther {
        Variant1,
        Variant2(u32),
        Variant3 {
            value: String,
        },
        #[serde(other)]
        Unknown,
    }

    let deserialized: OriginalWithOther =
        deserialize(Full::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, OriginalWithOther::Unknown);

    let extended_v5 = Extended::Variant5(true);
    let mut serialized = Vec::new();
    serialize(Full::new(), &mut serialized, &extended_v5).expect("serialization failed");
    let deserialized: OriginalWithOther =
        deserialize(Full::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, OriginalWithOther::Unknown);

    // Test compatibility with even more extended version
    let more_extended_v6 = MoreExtended::Variant6 { x: 10, y: 20 };
    let mut serialized = Vec::new();
    serialize(Full::new(), &mut serialized, &more_extended_v6).expect("serialization failed");

    // Should deserialize to Unknown in Extended enum
    let deserialized: Extended = deserialize(Full::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, Extended::Unknown);

    // Should also deserialize to Unknown in OriginalWithOther enum
    let deserialized: OriginalWithOther =
        deserialize(Full::new(), serialized.as_slice()).expect("deserialization failed");
    assert_eq!(deserialized, OriginalWithOther::Unknown);

    // Test that existing variants still work across all versions
    let more_extended_v1 = MoreExtended::Variant1;
    let extended_v1: Extended = transform(&more_extended_v1, Full::new());
    assert_eq!(extended_v1, Extended::Variant1);

    let original_v1: OriginalWithOther = transform(&more_extended_v1, Full::new());
    assert_eq!(original_v1, OriginalWithOther::Variant1);
}

#[test]
fn reordered_enum_variants_with_numerical_ids_full_encoding() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum Original {
        #[serde(rename = "_0")]
        MyLongVariantName(u32),
        #[serde(rename = "_1")]
        AnotherLongVariantName,
        #[serde(rename = "_2")]
        VariantWithFields {
            #[serde(rename = "_0")]
            value: u8,
        },
    }

    // The variants are reordered and a new one is inserted in the middle,
    // but their numerical identifiers are preserved.
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum Reordered {
        #[serde(rename = "_2")]
        VariantWithFields {
            #[serde(rename = "_0")]
            value: u8,
        },
        #[serde(rename = "_5")]
        AddedVariant(bool),
        #[serde(rename = "_1")]
        AnotherLongVariantName,
        #[serde(rename = "_0")]
        MyLongVariantName(u32),
    }

    let unit: Reordered = transform(&Original::AnotherLongVariantName, Full::new());
    assert_eq!(unit, Reordered::AnotherLongVariantName);

    let newtype: Reordered = transform(&Original::MyLongVariantName(42), Full::new());
    assert_eq!(newtype, Reordered::MyLongVariantName(42));

    let structed: Reordered = transform(&Original::VariantWithFields { value: 9 }, Full::new());
    assert_eq!(structed, Reordered::VariantWithFields { value: 9 });

    // A numerically identified variant occupies a single byte, which is about
    // the value alone, so the header is left out here.
    let mut serialized = Vec::new();
    serialize(Full::new().with_header(false), &mut serialized, &Original::AnotherLongVariantName).unwrap();
    assert_eq!(serialized.len(), 1);
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
struct AccountCredentials {
    id: String,
    #[serde(with = "pkcs8_serde")]
    key_pkcs8: Vec<u8>,
    directory: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    urls: Option<DirectoryUrls>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
struct DirectoryUrls {
    new_nonce: String,
    new_account: String,
    new_order: String,
    new_authz: Option<String>,
    revoke_cert: Option<String>,
    key_change: Option<String>,
}

mod pkcs8_serde {
    use std::fmt;

    use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine};
    use serde::{Deserializer, Serializer, de};

    pub fn serialize<S>(key_pkcs8: &[u8], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let encoded = BASE64_URL_SAFE_NO_PAD.encode(key_pkcs8.as_ref());
        serializer.serialize_str(&encoded)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
        struct Visitor;

        impl<'de> de::Visitor<'de> for Visitor {
            type Value = Vec<u8>;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a base64-encoded PKCS#8 private key")
            }

            fn visit_str<E>(self, v: &str) -> Result<Vec<u8>, E>
            where
                E: de::Error,
            {
                BASE64_URL_SAFE_NO_PAD.decode(v).map_err(de::Error::custom)
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

#[test]
fn account_credentials_full_with_urls() {
    let test_credentials = AccountCredentials {
        id: "test-account-123".to_string(),
        key_pkcs8: vec![0x30, 0x82, 0x01, 0x22, 0x30, 0x0D], // Mock PKCS#8 DER data
        directory: Some("https://acme-v02.api.letsencrypt.org/directory".to_string()),
        urls: Some(DirectoryUrls {
            new_nonce: "https://acme-v02.api.letsencrypt.org/acme/new-nonce".to_string(),
            new_account: "https://acme-v02.api.letsencrypt.org/acme/new-acct".to_string(),
            new_order: "https://acme-v02.api.letsencrypt.org/acme/new-order".to_string(),
            new_authz: Some("https://acme-v02.api.letsencrypt.org/acme/new-authz".to_string()),
            revoke_cert: Some("https://acme-v02.api.letsencrypt.org/acme/revoke-cert".to_string()),
            key_change: Some("https://acme-v02.api.letsencrypt.org/acme/key-change".to_string()),
        }),
    };

    let _: AccountCredentials = transform(&test_credentials, Full::new());
}

#[test]
fn account_credentials_slim_with_urls() {
    let test_credentials = AccountCredentials {
        id: "test-account-456".to_string(),
        key_pkcs8: vec![0x30, 0x82, 0x01, 0x22, 0x30, 0x0D], // Mock PKCS#8 DER data
        directory: Some("https://acme-v02.api.letsencrypt.org/directory".to_string()),
        urls: Some(DirectoryUrls {
            new_nonce: "https://acme-v02.api.letsencrypt.org/acme/new-nonce".to_string(),
            new_account: "https://acme-v02.api.letsencrypt.org/acme/new-acct".to_string(),
            new_order: "https://acme-v02.api.letsencrypt.org/acme/new-order".to_string(),
            new_authz: Some("https://acme-v02.api.letsencrypt.org/acme/new-authz".to_string()),
            revoke_cert: Some("https://acme-v02.api.letsencrypt.org/acme/revoke-cert".to_string()),
            key_change: Some("https://acme-v02.api.letsencrypt.org/acme/key-change".to_string()),
        }),
    };

    let _: AccountCredentials = transform(&test_credentials, Slim::new());
}

#[test]
fn account_credentials_full_without_urls() {
    let test_credentials = AccountCredentials {
        id: "test-account-789".to_string(),
        key_pkcs8: vec![0x30, 0x82, 0x01, 0x22, 0x30, 0x0D], // Mock PKCS#8 DER data
        directory: Some("https://acme-v02.api.letsencrypt.org/directory".to_string()),
        urls: None, // No URLs
    };

    let _: AccountCredentials = transform(&test_credentials, Full::new());
}

#[test]
fn account_credentials_slim_without_urls() {
    let test_credentials = AccountCredentials {
        id: "test-account-101".to_string(),
        key_pkcs8: vec![0x30, 0x82, 0x01, 0x22, 0x30, 0x0D], // Mock PKCS#8 DER data
        directory: Some("https://acme-v02.api.letsencrypt.org/directory".to_string()),
        urls: None, // No URLs - this will cause skip_serializing_if to omit the field
    };

    let _: AccountCredentials = transform(&test_credentials, Slim::new());
}

// =============================================================================
// Middle field add/remove tests
// =============================================================================

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support adding fields in the middle")]
fn added_struct_field_in_middle() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        f1: u32,
        f2: u32,
        f3: u32,
    }

    #[derive(Serialize, Deserialize)]
    struct B {
        f1: u32,
        #[serde(default = "mid_default")]
        f_mid: u32,
        f2: u32,
        f3: u32,
    }

    const fn mid_default() -> u32 {
        99
    }

    let a = A { f1: 1, f2: 2, f3: 3 };

    // Full mode: fields matched by name, so inserting in the middle works.
    let b: B = transform(&a, Full::new());
    assert_eq!(b.f1, a.f1);
    assert_eq!(b.f_mid, mid_default());
    assert_eq!(b.f2, a.f2);
    assert_eq!(b.f3, a.f3);
}

#[test]
fn removed_struct_field_from_middle() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        f1: u32,
        f2: u32,
        f3: u32,
    }

    // B drops f2 from the middle.
    #[derive(Serialize, Deserialize)]
    struct B {
        f1: u32,
        f3: u32,
    }

    let a = A { f1: 1, f2: 2, f3: 3 };

    // Full mode: fields matched by name, so removal from the middle works.
    let b: B = transform(&a, Full::new());
    assert_eq!(b.f1, a.f1);
    assert_eq!(b.f3, a.f3);
}

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support adding fields in the middle")]
fn added_and_removed_struct_fields_in_middle() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        f1: u32,
        f2: u32,
        f3: u32,
        f4: u32,
    }

    // B keeps f1 and f4, drops f2/f3, adds f_new in the middle.
    #[derive(Serialize, Deserialize)]
    struct B {
        f1: u32,
        #[serde(default = "new_default")]
        f_new: u32,
        f4: u32,
    }

    const fn new_default() -> u32 {
        77
    }

    let a = A { f1: 1, f2: 2, f3: 3, f4: 4 };

    let b: B = transform(&a, Full::new());
    assert_eq!(b.f1, a.f1);
    assert_eq!(b.f_new, new_default());
    assert_eq!(b.f4, a.f4);
}

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support adding fields in the middle")]
fn added_struct_variant_field_in_middle() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum A {
        V1,
        V2 { f1: u32, f2: u32, f3: u32 },
    }

    #[derive(Serialize, Deserialize)]
    enum B {
        V1,
        V2 {
            f1: u32,
            #[serde(default = "mid_default2")]
            f_mid: u32,
            f2: u32,
            f3: u32,
        },
    }

    const fn mid_default2() -> u32 {
        55
    }

    let a = A::V2 { f1: 1, f2: 2, f3: 3 };

    let b: B = transform(&a, Full::new());
    let B::V2 { f1, f_mid, f2, f3 } = b else { panic!("wrong variant") };
    assert_eq!(f1, 1);
    assert_eq!(f_mid, mid_default2());
    assert_eq!(f2, 2);
    assert_eq!(f3, 3);
}

#[test]
fn removed_struct_variant_field_from_middle() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum A {
        V1,
        V2 { f1: u32, f2: u32, f3: u32 },
    }

    #[derive(Serialize, Deserialize)]
    enum B {
        V1,
        V2 { f1: u32, f3: u32 },
    }

    let a = A::V2 { f1: 1, f2: 2, f3: 3 };

    let b: B = transform(&a, Full::new());
    let B::V2 { f1, f3 } = b else { panic!("wrong variant") };
    assert_eq!(f1, 1);
    assert_eq!(f3, 3);
}

#[test]
fn changed_fields_of_a_nested_struct() {
    // A struct that fills a field's block writes no field count, so the reader
    // finds the end of its fields by the end of the block. Adding, removing
    // and reordering fields has to keep working across that.
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct OuterA {
        #[serde(rename = "_0")]
        inner: InnerA,
        #[serde(rename = "_1")]
        after: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct InnerA {
        #[serde(default)]
        f1: u32,
        f2: String,
        #[serde(default)]
        f3: bool,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct OuterB {
        #[serde(rename = "_0")]
        inner: InnerB,
        #[serde(rename = "_1")]
        after: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct InnerB {
        f2: String,
        #[serde(default)]
        f4: Option<u32>,
    }

    let value = OuterA { inner: InnerA { f1: 7, f2: "x".into(), f3: true }, after: 300 };

    for cfg in [Full::new(), Full::new().with_version(Version::Postbag0_4)] {
        // Fields the reader does not know are skipped, one it never got
        // takes its default, and the field after the struct is still found.
        let b: OuterB = transform(&value, cfg);
        assert_eq!(b.inner.f2, "x");
        assert_eq!(b.inner.f4, None);
        assert_eq!(b.after, 300);
    }
}

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support adding fields in the middle")]
fn restored_fields_of_a_nested_struct() {
    // The other direction of `changed_fields_of_a_nested_struct`: the reader
    // knows more fields than it is sent, including one before a field it does
    // get, which is what the buffered path cannot do.
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Outer<T> {
        #[serde(rename = "_0")]
        inner: T,
        #[serde(rename = "_1")]
        after: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Sent {
        f2: String,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Expected {
        #[serde(default)]
        f1: u32,
        f2: String,
        #[serde(default)]
        f3: bool,
    }

    let value = Outer { inner: Sent { f2: "x".into() }, after: 300 };

    for cfg in [Full::new(), Full::new().with_version(Version::Postbag0_4)] {
        let got: Outer<Expected> = transform(&value, cfg);
        assert_eq!(got.inner, Expected { f1: 0, f2: "x".into(), f3: false });
        assert_eq!(got.after, 300);
    }
}

#[test]
fn a_nested_struct_that_loses_all_its_fields() {
    // The block is then empty, which the reader must read as "no fields"
    // rather than running off the end.
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Outer<T> {
        #[serde(rename = "_0")]
        inner: T,
        #[serde(rename = "_1")]
        after: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Empty {}

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Filled {
        #[serde(default)]
        f1: u32,
    }

    for cfg in [Full::new(), Full::new().with_version(Version::Postbag0_4)] {
        let value = Outer { inner: Empty {}, after: 300 };
        let grown: Outer<Filled> = transform(&value, cfg);
        assert_eq!(grown.inner.f1, 0);
        assert_eq!(grown.after, 300);

        let value = Outer { inner: Filled { f1: 7 }, after: 300 };
        let shrunk: Outer<Empty> = transform(&value, cfg);
        assert_eq!(shrunk.after, 300);
    }
}

#[test]
fn a_char_field_widened_to_a_string() {
    // A char and a string encode identically as a field value, so widening
    // one to the other is something people will do. Both directions have to
    // stay readable: with remoc the same pair of programs talks both ways, so
    // a widening that only works in one of them cannot be used at all.
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct AsChar {
        #[serde(rename = "_0")]
        unit: char,
        #[serde(rename = "_1")]
        after: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct AsString {
        #[serde(rename = "_0")]
        unit: String,
        #[serde(rename = "_1")]
        after: u32,
    }

    for cfg in [Full::new(), Full::new().with_version(Version::Postbag0_4)] {
        // The updated peer reads what the old one sends, exactly.
        let widened: AsString = transform(&AsChar { unit: '°', after: 300 }, cfg);
        assert_eq!(widened, AsString { unit: "°".into(), after: 300 });

        // The old peer reads what the updated one sends, keeping the first
        // character and — this is the point — the rest of the message.
        for sent in ["°C", "a", "hello, world"] {
            let narrowed: AsChar = transform(&AsString { unit: sent.into(), after: 300 }, cfg);
            assert_eq!(narrowed.unit, sent.chars().next().unwrap(), "reading {sent:?} as a char");
            assert_eq!(narrowed.after, 300, "the field after {sent:?} was still found");
        }

        // Nothing at all is still not a character.
        let empty = postbag::to_vec(cfg, &AsString { unit: String::new(), after: 300 }).unwrap();
        assert!(postbag::from_slice::<AsChar, _>(cfg, empty.as_slice()).is_err());
    }
}

#[test]
fn a_name_that_looks_numbered_but_is_not() {
    // `_07` parses as seven, but reading seven back gives `_7`. Encoding it
    // as a number would lose the field, so it is written out as a name.
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Padded {
        #[serde(rename = "_07")]
        #[serde(default)]
        padded: u32,
        #[serde(rename = "_7")]
        #[serde(default)]
        plain: u32,
    }

    let value = Padded { padded: 1, plain: 2 };

    for cfg in [Full::new(), Full::new().with_version(Version::Postbag0_4)] {
        let bytes = postbag::to_vec(cfg, &value).unwrap();
        let back: Padded = postbag::from_slice(cfg, bytes.as_slice()).unwrap();

        assert_eq!(back, value, "a padded name must not collide with its plain form");
        assert!(bytes.windows(3).any(|w| w == b"_07"), "the name should be written out");
    }
}

// =============================================================================
// `skip_serializing_if` tests
// =============================================================================

/// A struct that omits fields in the first, middle and last position.
///
/// Every skippable field also carries a `default`, since a field that is
/// absent from the data must still be filled in when deserializing.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
struct Skipping {
    #[serde(skip_serializing_if = "Option::is_none", default)]
    first: Option<u32>,
    second: String,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    middle: Vec<u8>,
    third: u64,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    last: Option<String>,
}

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support omitted fields in the middle")]
fn skip_serializing_if_full() {
    // Every combination of present and omitted fields round-trips, because
    // `Full` identifies each field by name and thus tolerates holes anywhere.
    for first in [None, Some(1)] {
        for middle in [Vec::new(), vec![7, 8]] {
            for last in [None, Some("l".to_string())] {
                let value = Skipping {
                    first,
                    second: "s".to_string(),
                    middle: middle.clone(),
                    third: 3,
                    last: last.clone(),
                };

                let back: Skipping = transform(&value, Full::new());
                assert_eq!(back, value, "an omitted field must round-trip under Full");
            }
        }
    }
}

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support omitted fields in the middle")]
fn skip_serializing_if_full_shrinks_the_data() {
    let full = Skipping {
        first: Some(1),
        second: "s".to_string(),
        middle: vec![7, 8],
        third: 3,
        last: Some("l".to_string()),
    };
    let sparse = Skipping { second: "s".to_string(), third: 3, ..Default::default() };

    let full_len = postbag::to_vec(Full::new(), &full).unwrap().len();
    let sparse_len = postbag::to_vec(Full::new(), &sparse).unwrap().len();

    assert!(sparse_len < full_len, "omitted fields must not be written");
}

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support omitted fields in the middle")]
fn skip_serializing_if_full_struct_variant() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum E {
        Variant {
            #[serde(skip_serializing_if = "Option::is_none", default)]
            first: Option<u32>,
            second: u32,
            #[serde(skip_serializing_if = "Option::is_none", default)]
            last: Option<u32>,
        },
    }

    for first in [None, Some(1)] {
        for last in [None, Some(9)] {
            let value = E::Variant { first, second: 2, last };
            let back: E = transform(&value, Full::new());
            assert_eq!(back, value, "an omitted variant field must round-trip under Full");
        }
    }
}

#[test]
#[cfg_attr(postbag_fast_compile, ignore = "fast_compile does not support omitted fields in the middle")]
fn skip_serializing_if_full_nested() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
    struct Outer {
        #[serde(skip_serializing_if = "Option::is_none", default)]
        before: Option<u32>,
        inner: Skipping,
        after: u32,
    }

    let value = Outer { before: None, inner: Skipping { third: 3, ..Default::default() }, after: 4 };

    let back: Outer = transform(&value, Full::new());
    assert_eq!(back, value, "omitted fields must round-trip when nested");
}

/// Under `Slim` a field carries no identifier, so an omitted field leaves a
/// hole that the deserializer cannot see: the fields that follow shift into
/// its place. Only trailing fields may be omitted.
#[test]
fn skip_serializing_if_slim_only_works_at_the_end() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
    struct Trailing {
        first: u32,
        second: u32,
        #[serde(skip_serializing_if = "is_zero", default)]
        last: u32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
    struct Middle {
        first: u32,
        #[serde(skip_serializing_if = "is_zero", default)]
        middle: u32,
        #[serde(default)]
        last: u32,
    }

    fn is_zero(value: &u32) -> bool {
        *value == 0
    }

    // A trailing field may be omitted: the field count states where the
    // fields end and the missing one falls back to its default.
    let trailing = Trailing { first: 1, second: 2, last: 0 };
    let bytes = postbag::to_vec(Slim::new(), &trailing).unwrap();
    let back: Trailing = postbag::from_slice(Slim::new(), bytes.as_slice()).unwrap();
    assert_eq!(back, trailing, "a trailing omitted field must round-trip under Slim");

    // A field omitted in the middle silently shifts the fields behind it.
    // Without the `default` on `last` this would at least fail loudly with
    // "invalid length", but the shift itself goes unnoticed.
    let middle = Middle { first: 1, middle: 0, last: 7 };
    let bytes = postbag::to_vec(Slim::new(), &middle).unwrap();
    let back: Middle = postbag::from_slice(Slim::new(), bytes.as_slice()).unwrap();
    assert_eq!(
        back,
        Middle { first: 1, middle: 7, last: 0 },
        "Slim cannot express a hole, so the following field takes its place"
    );
}