microrti-encoding 0.2.1

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
//! The encoding rules of IEEE 1516.2-2025 4.14, one test per rule, in the three layers of the crate: the
//! typed layer, the dynamic containers and the FOM-driven codec (feature `fom`).
//!
//! Every expected octet string is written out from the rule it checks (two's complement, byte order,
//! padding equations of 4.14.10), never taken from the output of the code under test.

mod common;

use common::{check, check_dynamic};
use microrti_encoding::*;

// ---------------------------------------------------------------------------------------------------
// FOM helpers
// ---------------------------------------------------------------------------------------------------

#[cfg(feature = "fom")]
mod fom_support {
    use microrti_encoding::fom::{FomCodec, Value};
    use microrti_fom::{Fdd, parse_module};

    /// The standard MIM with a module made of the given sections.
    pub fn fdd_with(body: &str) -> Fdd {
        let document = format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <objectModel xmlns=\"http://standards.ieee.org/IEEE1516-2025\">{body}</objectModel>"
        );
        let module = parse_module("omt.xml", document.as_bytes())
            .unwrap_or_else(|error| panic!("the test module does not parse: {error}"));
        Fdd::create(None, &[module])
            .unwrap_or_else(|error| panic!("the test module does not merge: {error}"))
            .0
    }

    /// Builder of a `dataTypes` section.
    #[derive(Default)]
    pub struct Tables {
        basic: Vec<String>,
        simple: Vec<String>,
        references: Vec<String>,
        enumerated: Vec<String>,
        arrays: Vec<String>,
        records: Vec<String>,
        variants: Vec<String>,
    }

    impl Tables {
        pub fn basic(mut self, name: &str, size: u32, interpretation: &str, endian: &str) -> Self {
            self.basic.push(format!(
                "<basicData><name>{name}</name><size>{size}</size>\
                 <interpretation>{interpretation}</interpretation><endian>{endian}</endian></basicData>"
            ));
            self
        }

        pub fn simple(mut self, name: &str, representation: &str) -> Self {
            self.simple.push(format!(
                "<simpleData><name>{name}</name><representation>{representation}</representation></simpleData>"
            ));
            self
        }

        pub fn reference(mut self, name: &str, representation: &str, class: &str, attribute: &str) -> Self {
            self.references.push(format!(
                "<referenceDataType><name>{name}</name><representation>{representation}</representation>\
                 <referenceClass>{class}</referenceClass><referencedAttribute>{attribute}\
                 </referencedAttribute></referenceDataType>"
            ));
            self
        }

        /// Enumerators with one or more values each.
        pub fn enumerated(
            mut self,
            name: &str,
            representation: &str,
            enumerators: &[(&str, &[i64])],
        ) -> Self {
            let enumerators: String = enumerators
                .iter()
                .map(|(name, values)| {
                    let values: String =
                        values.iter().map(|value| format!("<value>{value}</value>")).collect();
                    format!("<enumerator><name>{name}</name>{values}</enumerator>")
                })
                .collect();
            self.enumerated.push(format!(
                "<enumeratedData><name>{name}</name><representation>{representation}</representation>\
                 {enumerators}</enumeratedData>"
            ));
            self
        }

        pub fn array(mut self, name: &str, element: &str, cardinality: &str, encoding: &str) -> Self {
            self.arrays.push(format!(
                "<arrayData><name>{name}</name><dataType>{element}</dataType>\
                 <cardinality>{cardinality}</cardinality><encoding>{encoding}</encoding></arrayData>"
            ));
            self
        }

        pub fn record(mut self, name: &str, fields: &[(&str, &str)]) -> Self {
            let fields: String = fields
                .iter()
                .map(|(name, data_type)| {
                    format!("<field><name>{name}</name><dataType>{data_type}</dataType></field>")
                })
                .collect();
            self.records.push(format!(
                "<fixedRecordData><name>{name}</name><encoding>HLAfixedRecord</encoding>{fields}</fixedRecordData>"
            ));
            self
        }

        /// Alternatives are (enumerator set, name, data type); an empty name stands for "no data".
        pub fn variant(
            mut self,
            name: &str,
            encoding: &str,
            discriminant_type: &str,
            alternatives: &[(&str, &str, &str)],
        ) -> Self {
            let alternatives: String = alternatives
                .iter()
                .map(|(enumerator, name, data_type)| {
                    let data = if name.is_empty() {
                        String::new()
                    } else {
                        format!("<name>{name}</name><dataType>{data_type}</dataType>")
                    };
                    format!("<alternative><enumerator>{enumerator}</enumerator>{data}</alternative>")
                })
                .collect();
            self.variants.push(format!(
                "<variantRecordData><name>{name}</name><discriminant>D</discriminant>\
                 <dataType>{discriminant_type}</dataType>{alternatives}<encoding>{encoding}</encoding>\
                 </variantRecordData>"
            ));
            self
        }

        pub fn xml(&self) -> String {
            let table = |element: &str, entries: &[String]| {
                if entries.is_empty() {
                    String::new()
                } else {
                    format!("<{element}>{}</{element}>", entries.concat())
                }
            };
            format!(
                "<dataTypes>{}{}{}{}{}{}{}</dataTypes>",
                table("basicDataRepresentations", &self.basic),
                table("simpleDataTypes", &self.simple),
                table("referenceDataTypes", &self.references),
                table("enumeratedDataTypes", &self.enumerated),
                table("arrayDataTypes", &self.arrays),
                table("fixedRecordDataTypes", &self.records),
                table("variantRecordDataTypes", &self.variants),
            )
        }

        pub fn codec(&self) -> FomCodec {
            FomCodec::new(&fdd_with(&self.xml())).expect("the test data types resolve")
        }
    }

    /// Encoding and strict decoding of `value` as `name` give and take exactly `expected`.
    #[track_caller]
    pub fn both_ways(codec: &FomCodec, name: &str, value: &Value, expected: &[u8]) {
        assert_eq!(codec.encode(name, value).as_deref(), Ok(expected), "encoding {value} as {name}");
        assert_eq!(codec.decode(name, expected).as_ref(), Ok(value), "decoding {expected:02x?} as {name}");
    }

    pub fn mim() -> FomCodec {
        FomCodec::new(&Fdd::with_standard_mim()).expect("the MIM resolves")
    }
}

#[cfg(feature = "fom")]
use fom_support::{Tables, both_ways, mim};
#[cfg(feature = "fom")]
use microrti_encoding::fom::{Enumerator, Reason, Value};

// ---------------------------------------------------------------------------------------------------
// 4.14.3, table 29: the predefined basic data representations
// ---------------------------------------------------------------------------------------------------

/// Integers in two's complement (signed) or plain binary (unsigned), most
/// significant octet first for Big, last for Little; the octet boundary is the size (4.14.10, table 43).
#[test]
fn table_29_integers_in_the_typed_layer() {
    check(HLAinteger16BE(0x0102), &[0x01, 0x02]);
    check(HLAinteger16BE(-2), &[0xff, 0xfe]);
    check(HLAinteger16BE(i16::MIN), &[0x80, 0x00]);
    check(HLAinteger32BE(0x0102_0304), &[0x01, 0x02, 0x03, 0x04]);
    check(HLAinteger32BE(-2), &[0xff, 0xff, 0xff, 0xfe]);
    check(HLAinteger64BE(0x0102_0304_0506_0708), &[1, 2, 3, 4, 5, 6, 7, 8]);
    check(HLAinteger64BE(i64::MIN), &[0x80, 0, 0, 0, 0, 0, 0, 0]);
    check(HLAunsignedInteger16BE(0xfffe), &[0xff, 0xfe]);
    check(HLAunsignedInteger32BE(0xfffe_fdfc), &[0xff, 0xfe, 0xfd, 0xfc]);
    check(HLAunsignedInteger64BE(u64::MAX - 1), &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]);
    check(HLAoctetPairBE(0x0102), &[0x01, 0x02]);

    check(HLAinteger16LE(0x0102), &[0x02, 0x01]);
    check(HLAinteger16LE(-2), &[0xfe, 0xff]);
    check(HLAinteger32LE(0x0102_0304), &[0x04, 0x03, 0x02, 0x01]);
    check(HLAinteger32LE(-2), &[0xfe, 0xff, 0xff, 0xff]);
    check(HLAinteger64LE(0x0102_0304_0506_0708), &[8, 7, 6, 5, 4, 3, 2, 1]);
    check(HLAinteger64LE(i64::MIN), &[0, 0, 0, 0, 0, 0, 0, 0x80]);
    check(HLAunsignedInteger8(0xfe), &[0xfe]);
    check(HLAunsignedInteger16LE(0xfffe), &[0xfe, 0xff]);
    check(HLAunsignedInteger32LE(0xfffe_fdfc), &[0xfc, 0xfd, 0xfe, 0xff]);
    check(HLAunsignedInteger64LE(u64::MAX - 1), &[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
    check(HLAoctetPairLE(0x0102), &[0x02, 0x01]);
    check(HLAoctet(0xab), &[0xab]);

    let boundaries = [
        (HLAinteger16BE::OCTET_BOUNDARY, 2),
        (HLAinteger32BE::OCTET_BOUNDARY, 4),
        (HLAinteger64BE::OCTET_BOUNDARY, 8),
        (HLAunsignedInteger16BE::OCTET_BOUNDARY, 2),
        (HLAunsignedInteger32BE::OCTET_BOUNDARY, 4),
        (HLAunsignedInteger64BE::OCTET_BOUNDARY, 8),
        (HLAoctetPairBE::OCTET_BOUNDARY, 2),
        (HLAinteger16LE::OCTET_BOUNDARY, 2),
        (HLAinteger32LE::OCTET_BOUNDARY, 4),
        (HLAinteger64LE::OCTET_BOUNDARY, 8),
        (HLAunsignedInteger8::OCTET_BOUNDARY, 1),
        (HLAunsignedInteger16LE::OCTET_BOUNDARY, 2),
        (HLAunsignedInteger32LE::OCTET_BOUNDARY, 4),
        (HLAunsignedInteger64LE::OCTET_BOUNDARY, 8),
        (HLAoctetPairLE::OCTET_BOUNDARY, 2),
        (HLAoctet::OCTET_BOUNDARY, 1),
    ];
    for (position, (boundary, expected)) in boundaries.into_iter().enumerate() {
        assert_eq!(boundary, expected, "row {position}");
    }
}

/// IEEE 754 single and double precision, in both byte orders. -2.5 is
/// sign 1, exponent 1 (biased 0x80 / 0x400), fraction 0.25.
#[test]
fn table_29_floats_in_the_typed_layer() {
    check(HLAfloat32BE(-2.5), &[0xc0, 0x20, 0x00, 0x00]);
    check(HLAfloat32LE(-2.5), &[0x00, 0x00, 0x20, 0xc0]);
    check(HLAfloat64BE(-2.5), &[0xc0, 0x04, 0, 0, 0, 0, 0, 0]);
    check(HLAfloat64LE(-2.5), &[0, 0, 0, 0, 0, 0, 0x04, 0xc0]);
    check(HLAfloat64BE(1.0), &[0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);
    assert_eq!(HLAfloat32BE::OCTET_BOUNDARY, 4);
    assert_eq!(HLAfloat32LE::OCTET_BOUNDARY, 4);
    assert_eq!(HLAfloat64BE::OCTET_BOUNDARY, 8);
    assert_eq!(HLAfloat64LE::OCTET_BOUNDARY, 8);
    // Infinities and NaN keep their bit patterns.
    assert_eq!(encode_to_vec(&HLAfloat32BE(f32::INFINITY)), [0x7f, 0x80, 0, 0]);
    assert!(decode_from_slice_strict::<HLAfloat64LE>(&[0, 0, 0, 0, 0, 0, 0xf8, 0x7f]).unwrap().0.is_nan());
}

/// Table 29 through the FOM codec: each predefined representation by name, with its octet boundary
/// and the range of its interpretation column.
#[cfg(feature = "fom")]
#[test]
fn table_29_in_the_fom_codec() {
    let codec = mim();
    let rows: [(&str, Value, &[u8], usize); 20] = [
        ("HLAinteger16BE", Value::from(-2), &[0xff, 0xfe], 2),
        ("HLAinteger32BE", Value::from(0x0102_0304), &[1, 2, 3, 4], 4),
        ("HLAinteger64BE", Value::from(i64::MIN), &[0x80, 0, 0, 0, 0, 0, 0, 0], 8),
        ("HLAunsignedInteger16BE", Value::from(0xfffe), &[0xff, 0xfe], 2),
        ("HLAunsignedInteger32BE", Value::from(0xfffe_fdfcu32), &[0xff, 0xfe, 0xfd, 0xfc], 4),
        (
            "HLAunsignedInteger64BE",
            Value::from(u64::MAX - 1),
            &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe],
            8,
        ),
        ("HLAfloat32BE", Value::from(-2.5), &[0xc0, 0x20, 0, 0], 4),
        ("HLAfloat64BE", Value::from(-2.5), &[0xc0, 0x04, 0, 0, 0, 0, 0, 0], 8),
        ("HLAoctetPairBE", Value::from(0x0102), &[1, 2], 2),
        ("HLAinteger16LE", Value::from(-2), &[0xfe, 0xff], 2),
        ("HLAinteger32LE", Value::from(0x0102_0304), &[4, 3, 2, 1], 4),
        ("HLAinteger64LE", Value::from(i64::MIN), &[0, 0, 0, 0, 0, 0, 0, 0x80], 8),
        ("HLAunsignedInteger8", Value::from(0xfe), &[0xfe], 1),
        ("HLAunsignedInteger16LE", Value::from(0xfffe), &[0xfe, 0xff], 2),
        ("HLAunsignedInteger32LE", Value::from(0xfffe_fdfcu32), &[0xfc, 0xfd, 0xfe, 0xff], 4),
        (
            "HLAunsignedInteger64LE",
            Value::from(u64::MAX - 1),
            &[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
            8,
        ),
        ("HLAfloat32LE", Value::from(-2.5), &[0, 0, 0x20, 0xc0], 4),
        ("HLAfloat64LE", Value::from(-2.5), &[0, 0, 0, 0, 0, 0, 0x04, 0xc0], 8),
        ("HLAoctetPairLE", Value::from(0x0102), &[2, 1], 2),
        ("HLAoctet", Value::Octet(0xab), &[0xab], 1),
    ];
    for (name, value, expected, boundary) in rows {
        both_ways(&codec, name, &value, expected);
        assert_eq!(codec.octet_boundary(name), Some(boundary), "{name}");
        assert_eq!(codec.raw_reason(name), None, "{name}");
    }

    // The interpretation column: [-2^(n-1), 2^(n-1) - 1] for signed, [0, 2^n - 1] for unsigned.
    let ranges: [(&str, i128, i128); 15] = [
        ("HLAinteger16BE", -(1 << 15), (1 << 15) - 1),
        ("HLAinteger32BE", -(1 << 31), (1 << 31) - 1),
        ("HLAinteger64BE", -(1 << 63), (1 << 63) - 1),
        ("HLAunsignedInteger16BE", 0, (1 << 16) - 1),
        ("HLAunsignedInteger32BE", 0, (1 << 32) - 1),
        ("HLAunsignedInteger64BE", 0, (1 << 64) - 1),
        ("HLAinteger16LE", -(1 << 15), (1 << 15) - 1),
        ("HLAinteger32LE", -(1 << 31), (1 << 31) - 1),
        ("HLAinteger64LE", -(1 << 63), (1 << 63) - 1),
        ("HLAunsignedInteger8", 0, (1 << 8) - 1),
        ("HLAunsignedInteger16LE", 0, (1 << 16) - 1),
        ("HLAunsignedInteger32LE", 0, (1 << 32) - 1),
        ("HLAunsignedInteger64LE", 0, (1 << 64) - 1),
        ("HLAoctetPairBE", 0, (1 << 16) - 1),
        ("HLAoctetPairLE", 0, (1 << 16) - 1),
    ];
    for (name, low, high) in ranges {
        for inside in [low, high] {
            let bytes = codec.encode(name, &Value::Integer(inside)).unwrap_or_else(|error| panic!("{error}"));
            assert_eq!(codec.decode(name, &bytes), Ok(Value::Integer(inside)), "{name}");
        }
        for outside in [low - 1, high + 1] {
            let error = codec.encode(name, &Value::Integer(outside)).unwrap_err();
            assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{name}: {error}");
        }
    }
    // Single precision: a finite double beyond its range has no encoding.
    let error = codec.encode("HLAfloat32BE", &Value::from(1e39)).unwrap_err();
    assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
}

// ---------------------------------------------------------------------------------------------------
// 4.14.3 and 4.14.10: basic data representations of any size
// ---------------------------------------------------------------------------------------------------

/// A size that is no multiple of 8 bits is padded with bits up to the next multiple of 8, and
/// the octet boundary is the smallest power of two `b` with `8 * b` at least the size in bits.
#[cfg(feature = "fom")]
#[test]
fn basic_representations_of_any_size() {
    let codec = Tables::default()
        .basic("U24", 24, "Integer in the range [0, 2^24 - 1]", "Big")
        .basic("S24", 24, "Two's complement integer", "Little")
        .basic("U12", 12, "Integer in the range [0, 2^12 - 1]", "Big")
        .basic("S12", 12, "Two's complement integer", "Big")
        .basic("U4", 4, "Integer in the range [0, 15]", "Little")
        .basic("U40", 40, "Integer in the range [0, 2^40 - 1]", "Little")
        .basic("Opaque128", 128, "128-bit value", "Big")
        .basic("Opaque100", 100, "100-bit value", "Big")
        .basic("Opaque100LE", 100, "100-bit value", "Little")
        .basic("Huge", 2048, "2048-bit value", "Big")
        .record("OctetThenU24", &[("A", "HLAoctet"), ("B", "U24")])
        .record("OctetThenU40", &[("A", "HLAoctet"), ("B", "U40")])
        .codec();

    // Sizes in octets and octet boundaries.
    for (name, boundary) in [("U24", 4), ("S24", 4), ("U12", 2), ("S12", 2), ("U4", 1), ("U40", 8)] {
        assert_eq!(codec.octet_boundary(name), Some(boundary), "{name}");
    }
    assert_eq!(codec.octet_boundary("Opaque128"), Some(16));
    assert_eq!(codec.octet_boundary("Opaque100"), Some(16));

    // 24 bits: three octets; the boundary 4 puts three octets of padding after an octet.
    both_ways(&codec, "U24", &Value::from(0x01_0203), &[0x01, 0x02, 0x03]);
    both_ways(&codec, "S24", &Value::from(-2), &[0xfe, 0xff, 0xff]);
    both_ways(&codec, "S24", &Value::from(-(1 << 23)), &[0x00, 0x00, 0x80]);
    let record = Value::record([("A", Value::Octet(9)), ("B", Value::from(0x01_0203))]);
    both_ways(&codec, "OctetThenU24", &record, &[9, 0, 0, 0, 0x01, 0x02, 0x03]);
    // 40 bits: five octets at the boundary 8.
    both_ways(&codec, "U40", &Value::from(0x01_0203_0405i64), &[0x05, 0x04, 0x03, 0x02, 0x01]);
    let record = Value::record([("A", Value::Octet(9)), ("B", Value::from(0x01_0203_0405i64))]);
    both_ways(&codec, "OctetThenU40", &record, &[9, 0, 0, 0, 0, 0, 0, 0, 0x05, 0x04, 0x03, 0x02, 0x01]);

    // 12 bits: two octets whose four most significant bits are padding, zero, also for a negative value.
    both_ways(&codec, "U12", &Value::from(0xabc), &[0x0a, 0xbc]);
    both_ways(&codec, "S12", &Value::from(-1), &[0x0f, 0xff]);
    both_ways(&codec, "S12", &Value::from(-2048), &[0x08, 0x00]);
    both_ways(&codec, "S12", &Value::from(2047), &[0x07, 0xff]);
    both_ways(&codec, "U4", &Value::from(15), &[0x0f]);
    for (name, value) in [("U12", 1 << 12), ("S12", 2048), ("S12", -2049), ("U4", 16), ("U24", 1 << 24)] {
        let error = codec.encode(name, &Value::from(value)).unwrap_err();
        assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{name}: {error}");
    }
    // A padding bit that is set is ignored when decoding, like a padding octet: the value is the one the
    // same octets give with zero padding bits.
    let set_padding: [(&str, &[u8], Value); 3] = [
        ("U12", &[0x1a, 0xbc], Value::from(0xabc)),
        ("S12", &[0xff, 0xff], Value::from(-1)),
        ("U4", &[0x1f], Value::from(15)),
    ];
    for (name, octets, value) in set_padding {
        assert_eq!(codec.decode(name, octets).as_ref(), Ok(&value), "{name}");
    }

    // More than 64 bits: the octets as they travel.
    let wide: Vec<u8> = (0x10..0x20).collect();
    both_ways(&codec, "Opaque128", &Value::bytes(wide.clone()), &wide);
    let error = codec.encode("Opaque128", &Value::bytes([1u8, 2])).unwrap_err();
    assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
    // 100 bits: 13 octets; the four padding bits are the high bits of the most significant octet.
    let mut hundred = vec![0x0f];
    hundred.extend([0xff; 12]);
    both_ways(&codec, "Opaque100", &Value::bytes(hundred.clone()), &hundred);
    let mut padded = hundred.clone();
    padded[0] = 0x1f;
    assert!(codec.encode("Opaque100", &Value::bytes(padded.clone())).is_err());
    assert_eq!(codec.decode("Opaque100", &padded), Ok(Value::bytes(hundred)));
    let mut little = vec![0xff; 12];
    little.push(0x0f);
    both_ways(&codec, "Opaque100LE", &Value::bytes(little.clone()), &little);
    let mut padded = little.clone();
    padded[12] = 0xff;
    assert_eq!(codec.decode("Opaque100LE", &padded), Ok(Value::bytes(little)));

    // A size beyond what the codec resolves stays raw.
    assert!(codec.raw_reason("Huge").is_some_and(|reason| reason.contains("2048 bits")));
}

/// The octet boundary formula of 4.14.10 for sizes around each power of two.
#[cfg(feature = "fom")]
#[test]
fn octet_boundary_formula() {
    let sizes = [1, 7, 8, 9, 15, 16, 17, 24, 31, 32, 33, 48, 63, 64, 65, 127, 128, 129, 255, 256, 257, 1024];
    let mut tables = Tables::default();
    for bits in sizes {
        tables = tables.basic(&format!("B{bits}"), bits, "Integer in the range [0, 2^n - 1]", "Big");
    }
    let codec = tables.codec();
    for bits in sizes {
        // Smallest 2^n with 8 * 2^n >= bits.
        let mut expected = 1;
        while 8 * expected < bits as usize {
            expected *= 2;
        }
        assert_eq!(codec.octet_boundary(&format!("B{bits}")), Some(expected), "{bits} bits");
    }
}

// ---------------------------------------------------------------------------------------------------
// 4.14.4: simple data types
// ---------------------------------------------------------------------------------------------------

/// The five predefined simple data types of table 31 are their representations.
#[test]
fn table_31_in_the_typed_layer() {
    check(HLAASCIIchar(b'a'), &[0x61]);
    check(HLAunicodeChar(0x00e9), &[0x00, 0xe9]);
    check(HLAunicodeChar(0x20ac), &[0x20, 0xac]);
    check(HLAbyte(0xff), &[0xff]);
    let time: HLAinteger64Time = HLAinteger64BE(-2);
    check(time, &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]);
    let time: HLAfloat64Time = HLAfloat64BE(-2.5);
    check(time, &[0xc0, 0x04, 0, 0, 0, 0, 0, 0]);
    assert_eq!(HLAASCIIchar::OCTET_BOUNDARY, 1);
    assert_eq!(HLAunicodeChar::OCTET_BOUNDARY, 2);
    assert_eq!(HLAbyte::OCTET_BOUNDARY, 1);
}

/// The same through the FOM codec, and a user-defined simple data type (table 32) is encoded as
/// its representation, with its octet boundary.
#[cfg(feature = "fom")]
#[test]
fn table_31_and_32_in_the_fom_codec() {
    let codec = Tables::default()
        .basic("UnsignedShort", 16, "Integer in the range [0, 2^16 - 1]", "Big")
        .simple("DollarRate", "HLAfloat32BE")
        .simple("DrinkCount", "UnsignedShort")
        .simple("Years", "HLAinteger32BE")
        .codec();
    both_ways(&codec, "HLAASCIIchar", &Value::Char('a'), &[0x61]);
    both_ways(&codec, "HLAunicodeChar", &Value::Char('\u{e9}'), &[0x00, 0xe9]);
    both_ways(&codec, "HLAunicodeChar", &Value::Char('\u{20ac}'), &[0x20, 0xac]);
    both_ways(&codec, "HLAbyte", &Value::Octet(0xff), &[0xff]);
    both_ways(
        &codec,
        "HLAinteger64Time",
        &Value::from(-2),
        &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe],
    );
    both_ways(&codec, "HLAfloat64Time", &Value::from(-2.5), &[0xc0, 0x04, 0, 0, 0, 0, 0, 0]);
    both_ways(&codec, "DollarRate", &Value::from(2.5), &[0x40, 0x20, 0, 0]);
    both_ways(&codec, "DrinkCount", &Value::from(3), &[0x00, 0x03]);
    both_ways(&codec, "Years", &Value::from(-1), &[0xff, 0xff, 0xff, 0xff]);
    for (name, boundary) in [("DollarRate", 4), ("DrinkCount", 2), ("Years", 4), ("HLAunicodeChar", 2)] {
        assert_eq!(codec.octet_boundary(name), Some(boundary), "{name}");
    }

    // ASCII is seven bits; one HLAunicodeChar is one UTF-16 code unit, so no surrogate and nothing
    // outside the basic multilingual plane.
    for (name, character) in [("HLAASCIIchar", '\u{e9}'), ("HLAunicodeChar", '\u{1f600}')] {
        let error = codec.encode(name, &Value::Char(character)).unwrap_err();
        assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
    }
    assert!(matches!(
        codec.decode("HLAASCIIchar", &[0x80]).unwrap_err().reason(),
        Some(Reason::InvalidValue { .. })
    ));
    assert!(matches!(
        codec.decode("HLAunicodeChar", &[0xd8, 0x3d]).unwrap_err().reason(),
        Some(Reason::InvalidValue { .. })
    ));
}

// ---------------------------------------------------------------------------------------------------
// 4.14.5: enumerated data types
// ---------------------------------------------------------------------------------------------------

hla_enumerated! {
    /// An enumeration carried by a little-endian 16-bit representation.
    enum Level: HLAinteger16LE {
        Low = -1,
        High = 0x0102,
    }
}

/// An enumerator travels as its value in the representation of the enumerated data type, and
/// HLAboolean is HLAfalse = 0, HLAtrue = 1 in an HLAinteger32BE (table 33).
#[test]
fn enumerated_types_in_the_typed_layer() {
    check(HLAboolean(false), &[0, 0, 0, 0]);
    check(HLAboolean(true), &[0, 0, 0, 1]);
    assert_eq!(HLAboolean::OCTET_BOUNDARY, 4);
    check(Level::Low, &[0xff, 0xff]);
    check(Level::High, &[0x02, 0x01]);
    assert_eq!(Level::OCTET_BOUNDARY, 2);
    // A value that is no enumerator: the typed layer refuses it.
    assert!(matches!(decode_from_slice::<Level>(&[0, 0]), Err(DecoderError::InvalidEnumerator { .. })));
    assert!(matches!(decode_from_slice::<HLAboolean>(&[0, 0, 0, 2]), Err(DecoderError::InvalidValue { .. })));
}

/// The same through the FOM codec, with enumerators of several values each (4.14.5, Values column)
/// and representations of other sizes.
#[cfg(feature = "fom")]
#[test]
fn enumerated_types_in_the_fom_codec() {
    let codec = Tables::default()
        .basic("U24", 24, "Integer in the range [0, 2^24 - 1]", "Big")
        .enumerated("Color", "HLAoctet", &[("Red", &[1, 2]), ("Green", &[3])])
        .enumerated("Level", "HLAinteger16LE", &[("Low", &[-1]), ("High", &[0x0102])])
        .enumerated("Wide", "U24", &[("Far", &[0x01_0203])])
        .codec();
    both_ways(&codec, "HLAboolean", &Value::Bool(true), &[0, 0, 0, 1]);
    both_ways(&codec, "HLAboolean", &Value::Bool(false), &[0, 0, 0, 0]);
    both_ways(&codec, "Level", &Value::enumerator_with("Low", -1), &[0xff, 0xff]);
    both_ways(&codec, "Level", &Value::enumerator_with("High", 0x0102), &[0x02, 0x01]);
    both_ways(&codec, "Wide", &Value::enumerator_with("Far", 0x01_0203), &[0x01, 0x02, 0x03]);
    assert_eq!(codec.octet_boundary("Color"), Some(1));
    assert_eq!(codec.octet_boundary("Level"), Some(2));
    assert_eq!(codec.octet_boundary("Wide"), Some(4));

    // Every value of an enumerator maps to it; the name alone encodes the first value.
    both_ways(&codec, "Color", &Value::enumerator_with("Red", 2), &[2]);
    both_ways(&codec, "Color", &Value::enumerator_with("Red", 1), &[1]);
    assert_eq!(codec.encode("Color", &Value::enumerator("Red")), Ok(vec![1]));
    assert_eq!(codec.encode("Color", &Value::from(3)), Ok(vec![3]));
    let error = codec.encode("Color", &Value::enumerator_with("Green", 2)).unwrap_err();
    assert!(matches!(error.reason(), Some(Reason::UnknownEnumerator { .. })), "{error}");

    // A value that is no enumerator: decoded without a name, refused when encoding.
    assert_eq!(codec.decode("Color", &[9]), Ok(Value::enumerator_value(9)));
    assert_eq!(codec.decode("HLAboolean", &[0, 0, 0, 2]), Ok(Value::enumerator_value(2)));
    let error = codec.encode("Color", &Value::enumerator_value(9)).unwrap_err();
    assert!(matches!(error.reason(), Some(Reason::UnknownEnumerator { .. })), "{error}");
}

// ---------------------------------------------------------------------------------------------------
// 4.14.6: array data types
// ---------------------------------------------------------------------------------------------------

/// The four predefined arrays of table 35. The strings and the opaque data are HLAvariableArrays
/// (an HLAinteger32BE count, then the elements); HLAtoken has no octets at all.
#[test]
fn table_35_in_the_typed_layer() {
    check(HLAASCIIstring::new("ab").unwrap(), &[0, 0, 0, 2, 0x61, 0x62]);
    check(HLAASCIIstring::default(), &[0, 0, 0, 0]);
    // UTF-16 code units, most significant octet first; the count is the number of code units.
    check(HLAunicodeString::new("a\u{e9}"), &[0, 0, 0, 2, 0x00, 0x61, 0x00, 0xe9]);
    check(HLAunicodeString::new("\u{1f600}"), &[0, 0, 0, 2, 0xd8, 0x3d, 0xde, 0x00]);
    check(HLAopaqueData::new([1u8, 2, 3]), &[0, 0, 0, 3, 1, 2, 3]);
    let token: HLAtoken = [];
    check(token, &[]);
    assert_eq!(HLAASCIIstring::OCTET_BOUNDARY, 4);
    assert_eq!(HLAunicodeString::OCTET_BOUNDARY, 4);
    assert_eq!(HLAopaqueData::OCTET_BOUNDARY, 4);
    assert_eq!(HLAtoken::OCTET_BOUNDARY, 1);
    // A fixed cardinality: the elements without a count.
    check([HLAinteger16BE(1), HLAinteger16BE(-1), HLAinteger16BE(2)], &[0, 1, 0xff, 0xff, 0, 2]);

    assert!(decode_from_slice::<HLAASCIIstring>(&[0, 0, 0, 1, 0x80]).is_err());
    assert!(decode_from_slice::<HLAunicodeString>(&[0, 0, 0, 1, 0xd8, 0x3d]).is_err());
}

/// The same through the FOM codec, with the cardinalities of 4.14.6: a fixed number, a range, Dynamic
/// and several dimensions (one array per dimension, the first one outermost).
#[cfg(feature = "fom")]
#[test]
fn arrays_in_the_fom_codec() {
    let codec = Tables::default()
        .array("Three", "HLAinteger16BE", "3", "HLAfixedArray")
        .array("Bounded", "HLAinteger16BE", "[1..2]", "HLAvariableArray")
        .array("Grid", "HLAinteger16BE", "2,3", "HLAfixedArray")
        .array("Ragged", "HLAinteger16BE", "Dynamic,Dynamic", "HLAvariableArray")
        .record("TokenInside", &[("A", "HLAoctet"), ("T", "HLAtoken"), ("B", "HLAoctet")])
        .codec();
    both_ways(&codec, "HLAASCIIstring", &Value::from("ab"), &[0, 0, 0, 2, 0x61, 0x62]);
    both_ways(&codec, "HLAunicodeString", &Value::from("a\u{e9}"), &[0, 0, 0, 2, 0x00, 0x61, 0x00, 0xe9]);
    both_ways(&codec, "HLAunicodeString", &Value::from("\u{1f600}"), &[0, 0, 0, 2, 0xd8, 0x3d, 0xde, 0x00]);
    both_ways(&codec, "HLAopaqueData", &Value::bytes([1u8, 2, 3]), &[0, 0, 0, 3, 1, 2, 3]);
    both_ways(&codec, "HLAtoken", &Value::bytes([]), &[]);
    assert_eq!(codec.octet_boundary("HLAtoken"), Some(1));
    for name in ["HLAASCIIstring", "HLAunicodeString", "HLAopaqueData"] {
        assert_eq!(codec.octet_boundary(name), Some(4), "{name}");
    }
    let record = Value::record([("A", Value::Octet(1)), ("T", Value::bytes([])), ("B", Value::Octet(2))]);
    both_ways(&codec, "TokenInside", &record, &[1, 2]);

    both_ways(&codec, "Three", &Value::array([1, -1, 2]), &[0, 1, 0xff, 0xff, 0, 2]);
    assert!(codec.encode("Three", &Value::array([1, 2])).is_err());
    both_ways(&codec, "Bounded", &Value::array([1, 2]), &[0, 0, 0, 2, 0, 1, 0, 2]);
    assert!(codec.encode("Bounded", &Value::array([1, 2, 3])).is_err());
    // Outside the range, but well formed: passed on when decoding (4.14.6 says nothing of the decoder).
    assert_eq!(codec.decode("Bounded", &[0, 0, 0, 0]), Ok(Value::Array(vec![])));

    // Two fixed dimensions: the same octets as six elements in a row.
    let grid = Value::array([Value::array([1, 2, 3]), Value::array([4, 5, 6])]);
    both_ways(&codec, "Grid", &grid, &[0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6]);
    // Two variable dimensions: each inner array has its count. Outer: count, no padding (boundary 4);
    // first inner array 6 octets, padded to 8; second inner array 8 octets.
    let ragged = Value::array([Value::array([1]), Value::array([2, 3])]);
    let expected = [0, 0, 0, 2, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 2, 0, 2, 0, 3];
    both_ways(&codec, "Ragged", &ragged, &expected);
}

// ---------------------------------------------------------------------------------------------------
// 4.14.7: fixed record data types
// ---------------------------------------------------------------------------------------------------

hla_fixed_record! {
    /// `ServiceStat` of table 38.
    struct ServiceStat {
        entree_ok: HLAboolean,
        veggy1_ok: HLAboolean,
        veggy2_ok: HLAboolean,
    }
}

hla_fixed_record! {
    /// `AddressType` of table 38.
    struct AddressType {
        name: HLAASCIIstring,
        street: HLAASCIIstring,
        city: HLAASCIIstring,
        state: HLAASCIIstring,
        zip: HLAASCIIstring,
    }
}

fn ascii(text: &str) -> HLAASCIIstring {
    HLAASCIIstring::new(text).unwrap()
}

/// The `AddressType` sample and its octets: each string is a count and its characters, padded to the
/// boundary 4 of the next string, nothing after the last one.
fn address_octets() -> Vec<u8> {
    let mut octets = vec![0, 0, 0, 2, b'A', b'l', 0, 0]; // Name, 2 octets of padding
    octets.extend([0, 0, 0, 1, b'1', 0, 0, 0]); // Street, 3 octets of padding
    octets.extend([0, 0, 0, 0]); // City, empty
    octets.extend([0, 0, 0, 2, b'C', b'A', 0, 0]); // State, 2 octets of padding
    octets.extend([0, 0, 0, 1, b'9']); // Zip, last: no padding
    octets
}

/// The fields in the order of their declaration, the first at offset 0 (table 38).
#[test]
fn fixed_records_in_the_typed_and_dynamic_layers() {
    let stat = ServiceStat {
        entree_ok: HLAboolean(true),
        veggy1_ok: HLAboolean(false),
        veggy2_ok: HLAboolean(true),
    };
    check(stat, &[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]);
    let address = AddressType {
        name: ascii("Al"),
        street: ascii("1"),
        city: ascii(""),
        state: ascii("CA"),
        zip: ascii("9"),
    };
    check(address, &address_octets());

    let dynamic = HLAfixedRecord::new().with(HLAboolean(true)).with(HLAboolean(false)).with(HLAboolean(true));
    let blank = HLAfixedRecord::new().with(HLAboolean(false)).with(HLAboolean(false)).with(HLAboolean(false));
    check_dynamic(&dynamic, blank, &[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]);
}

/// The same through the FOM codec; the value may name the fields in any order, the octets follow
/// the declaration.
#[cfg(feature = "fom")]
#[test]
fn fixed_records_in_the_fom_codec() {
    let codec = Tables::default()
        .record(
            "ServiceStat",
            &[("EntreeOk", "HLAboolean"), ("Veggy1Ok", "HLAboolean"), ("Veggy2Ok", "HLAboolean")],
        )
        .record(
            "AddressType",
            &[
                ("Name", "HLAASCIIstring"),
                ("Street", "HLAASCIIstring"),
                ("City", "HLAASCIIstring"),
                ("State", "HLAASCIIstring"),
                ("Zip", "HLAASCIIstring"),
            ],
        )
        .codec();
    let stat = Value::record([("EntreeOk", true), ("Veggy1Ok", false), ("Veggy2Ok", true)]);
    both_ways(&codec, "ServiceStat", &stat, &[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]);
    let reversed = Value::record([("Veggy2Ok", true), ("Veggy1Ok", false), ("EntreeOk", true)]);
    assert_eq!(codec.encode("ServiceStat", &reversed), Ok(vec![0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]));
    let address =
        Value::record([("Name", "Al"), ("Street", "1"), ("City", ""), ("State", "CA"), ("Zip", "9")]);
    both_ways(&codec, "AddressType", &address, &address_octets());
    assert_eq!(codec.octet_boundary("AddressType"), Some(4));

    let missing = Value::record([("EntreeOk", true), ("Veggy1Ok", false)]);
    assert!(matches!(
        codec.encode("ServiceStat", &missing).unwrap_err().reason(),
        Some(Reason::Field { .. })
    ));
    let extra =
        Value::record([("EntreeOk", true), ("Veggy1Ok", false), ("Veggy2Ok", true), ("Dessert", true)]);
    assert!(matches!(codec.encode("ServiceStat", &extra).unwrap_err().reason(), Some(Reason::Field { .. })));
}

// ---------------------------------------------------------------------------------------------------
// 4.14.8: variant record data types
// ---------------------------------------------------------------------------------------------------

/// The enumerated data types of table 34 used by table 40.
#[cfg(feature = "fom")]
fn table_34() -> Tables {
    Tables::default()
        .enumerated(
            "ExperienceLevel",
            "HLAinteger32BE",
            &[
                ("Trainee", &[0]),
                ("Apprentice", &[1]),
                ("Journeyman", &[2]),
                ("Senior", &[3]),
                ("Temporary", &[4]),
                ("Master", &[5]),
            ],
        )
        .enumerated("DrinkType", "HLAinteger32BE", &[("Margarita", &[1]), ("DryMartini", &[2])])
        .simple("RateScale", "HLAinteger32BE")
        .simple("FruitCount", "HLAinteger32BE")
}

/// The two examples of table 40. ServerValue is an HLAvariantRecord with an HLAother alternative,
/// DrinkGarnish an HLAextendableVariantRecord.
#[cfg(feature = "fom")]
#[test]
fn table_40_in_the_fom_codec() {
    let codec = table_34()
        .variant(
            "ServerValue",
            "HLAvariantRecord",
            "ExperienceLevel",
            &[
                ("Trainee", "CoursePassed", "HLAboolean"),
                ("Temporary", "TempAgency", "HLAunicodeString"),
                ("HLAother", "Rating", "RateScale"),
            ],
        )
        .variant(
            "DrinkGarnish",
            "HLAextendableVariantRecord",
            "DrinkType",
            &[("Margarita", "HasSaltRim", "HLAboolean"), ("DryMartini", "OliveCount", "FruitCount")],
        )
        .codec();
    // Every alternative has the octet boundary 4, as has the discriminant: no padding.
    let trainee = Value::variant_named(Enumerator::new("Trainee", 0), "CoursePassed", true);
    both_ways(&codec, "ServerValue", &trainee, &[0, 0, 0, 0, 0, 0, 0, 1]);
    let temporary = Value::variant_named(Enumerator::new("Temporary", 4), "TempAgency", "Ab");
    both_ways(&codec, "ServerValue", &temporary, &[0, 0, 0, 4, 0, 0, 0, 2, 0, b'A', 0, b'b']);
    // HLAother: every enumerator that no other row names.
    for (name, value) in [("Apprentice", 1u8), ("Journeyman", 2), ("Senior", 3), ("Master", 5)] {
        let rated = Value::variant_named(Enumerator::new(name, value), "Rating", 7);
        both_ways(&codec, "ServerValue", &rated, &[0, 0, 0, value, 0, 0, 0, 7]);
    }
    // DrinkGarnish: discriminant, encoded_length, alternative.
    let salt = Value::variant_named(Enumerator::new("Margarita", 1), "HasSaltRim", true);
    both_ways(&codec, "DrinkGarnish", &salt, &[0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 1]);
    let olives = Value::variant_named(Enumerator::new("DryMartini", 2), "OliveCount", 3);
    both_ways(&codec, "DrinkGarnish", &olives, &[0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 3]);
    // The alternative named in the value must be the one the discriminant selects.
    let wrong = Value::variant_named(Enumerator::new("Trainee", 0), "Rating", 7);
    assert!(matches!(
        codec.encode("ServerValue", &wrong).unwrap_err().reason(),
        Some(Reason::Alternative { .. })
    ));
}

/// The enumerator column holds single enumerators, comma separated lists and ranges; a range covers
/// the enumerators between its ends in the order of the enumerated data type, not by value.
#[cfg(feature = "fom")]
#[test]
fn enumerator_sets_of_a_variant_record() {
    let codec = Tables::default()
        .enumerated("Kind", "HLAoctet", &[("P", &[10]), ("Q", &[5]), ("R", &[7]), ("S", &[1]), ("T", &[2])])
        .variant(
            "Sets",
            "HLAvariantRecord",
            "Kind",
            &[
                ("P, S", "Listed", "HLAoctet"),
                ("[Q..R]", "Ranged", "HLAinteger16BE"),
                ("T", "Single", "HLAbyte"),
            ],
        )
        .codec();
    // V = 2 (largest alternative boundary): one octet of padding after the discriminant.
    let cases: [(&str, u8, &str, Value, Vec<u8>); 5] = [
        ("P", 10, "Listed", Value::Octet(9), vec![10, 0, 9]),
        ("S", 1, "Listed", Value::Octet(9), vec![1, 0, 9]),
        ("Q", 5, "Ranged", Value::from(-2), vec![5, 0, 0xff, 0xfe]),
        ("R", 7, "Ranged", Value::from(-2), vec![7, 0, 0xff, 0xfe]),
        ("T", 2, "Single", Value::Octet(9), vec![2, 0, 9]),
    ];
    for (enumerator, number, alternative, value, expected) in cases {
        let variant = Value::variant_named(Enumerator::new(enumerator, number), alternative, value);
        both_ways(&codec, "Sets", &variant, &expected);
    }

    let codec = Tables::default()
        .enumerated("Kind", "HLAoctet", &[("P", &[10]), ("Q", &[5]), ("R", &[7])])
        .variant(
            "ByOrder",
            "HLAvariantRecord",
            "Kind",
            &[("[P..Q]", "Low", "HLAoctet"), ("R", "High", "HLAinteger16BE")],
        )
        .codec();
    // R lies between Q and P by value but not by declaration: it keeps its own alternative.
    let high = Value::variant_named(Enumerator::new("R", 7), "High", 1);
    both_ways(&codec, "ByOrder", &high, &[7, 0, 0, 1]);
    let low = Value::variant_named(Enumerator::new("Q", 5), "Low", Value::Octet(1));
    both_ways(&codec, "ByOrder", &low, &[5, 0, 1]);
}

// ---------------------------------------------------------------------------------------------------
// 4.14.9: reference data types
// ---------------------------------------------------------------------------------------------------

/// A reference is encoded as its representation, which may be any data type (6.2.17): a name as an
/// HLAunicodeString (table 42), a handle as HLAobjectInstanceHandle.
#[cfg(feature = "fom")]
#[test]
fn reference_types_in_the_fom_codec() {
    use microrti_encoding::fom::FomCodec;

    let objects = "<objects><objectClass><name>HLAobjectRoot</name><objectClass><name>Employee</name>\
         <sharing>PublishSubscribe</sharing><attribute><name>Name</name><dataType>HLAunicodeString</dataType>\
         <updateType>Static</updateType><updateCondition>NA</updateCondition><ownership>NoTransfer</ownership>\
         <sharing>PublishSubscribe</sharing><transportation>HLAreliable</transportation><order>Receive</order>\
         </attribute></objectClass></objectClass></objects>";
    let tables = Tables::default()
        .reference("EmployeeReference", "HLAunicodeString", "HLAobjectRoot.Employee", "Name")
        .reference(
            "EmployeeHandle",
            "HLAobjectInstanceHandle",
            "HLAobjectRoot.Employee",
            "HLAobjectInstanceHandle",
        )
        .record("Shift", &[("Hours", "HLAoctet"), ("Who", "EmployeeReference")]);
    let codec = FomCodec::new(&fom_support::fdd_with(&format!("{objects}{}", tables.xml()))).unwrap();

    both_ways(&codec, "EmployeeReference", &Value::from("Al"), &[0, 0, 0, 2, 0, b'A', 0, b'l']);
    both_ways(&codec, "EmployeeHandle", &Value::handle([0u8, 0, 0, 7]), &[0, 0, 0, 4, 0, 0, 0, 7]);
    assert_eq!(codec.octet_boundary("EmployeeReference"), Some(4));
    // Inside a record the reference has the octet boundary of its representation.
    let shift = Value::record([("Hours", Value::Octet(8)), ("Who", Value::from("Al"))]);
    both_ways(&codec, "Shift", &shift, &[8, 0, 0, 0, 0, 0, 0, 2, 0, b'A', 0, b'l']);
}

// ---------------------------------------------------------------------------------------------------
// 4.14.10: rules common to the constructed data types
// ---------------------------------------------------------------------------------------------------

hla_fixed_record! {
    /// The example of 4.14.10: an HLAboolean, an HLAoctet and an HLAfloat64BE.
    struct BooleanOctetFloat {
        flag: HLAboolean,
        octet: HLAoctet,
        value: HLAfloat64BE,
    }
}

hla_fixed_record! {
    /// A record that contains the previous one.
    struct Container {
        first: HLAoctet,
        inner: BooleanOctetFloat,
    }
}

hla_fixed_record! {
    struct OctetThenInteger {
        octet: HLAoctet,
        integer: HLAinteger32BE,
    }
}

hla_variant_record! {
    enum OctetOrFloat: HLAoctet {
        Octet(HLAoctet) = HLAoctet(1),
        Float(HLAfloat64BE) = HLAoctet(2),
    }
}

/// The octet boundary of a constructed data type is the largest octet boundary of its components:
/// 8 for the example of 4.14.10, and at least 8 for anything that contains it.
#[test]
fn octet_boundary_of_constructed_types() {
    assert_eq!(BooleanOctetFloat::OCTET_BOUNDARY, 8);
    assert_eq!(Container::OCTET_BOUNDARY, 8);
    assert_eq!(<[BooleanOctetFloat; 2]>::OCTET_BOUNDARY, 8);
    assert_eq!(<Vec<BooleanOctetFloat>>::OCTET_BOUNDARY, 8);
    // A variable array is at least 4 (its count), a fixed array the boundary of its elements.
    assert_eq!(<Vec<HLAoctet>>::OCTET_BOUNDARY, 4);
    assert_eq!(<[HLAoctet; 3]>::OCTET_BOUNDARY, 1);
    // A variant record: the discriminant and every alternative.
    assert_eq!(OctetOrFloat::OCTET_BOUNDARY, 8);

    // The same in the dynamic containers.
    let record = HLAfixedRecord::new().with(HLAboolean(false)).with(HLAoctet(0)).with(HLAfloat64BE(0.0));
    assert_eq!(record.octet_boundary(), 8);
    assert_eq!(HLAfixedRecord::new().with(HLAoctet(0)).with(record.clone()).octet_boundary(), 8);
    assert_eq!(HLAvariableArray::new(HLAoctet(0)).octet_boundary(), 4);
    assert_eq!(HLAfixedArray::new(HLAinteger16BE(0), 3).octet_boundary(), 2);
    let mut variant = HLAvariantRecord::new(HLAoctet(0));
    variant.set_variant(HLAoctet(1), HLAoctet(0)).unwrap();
    variant.set_variant(HLAoctet(2), HLAfloat64BE(0.0)).unwrap();
    assert_eq!(variant.octet_boundary(), 8);

    // The containing record puts 7 octets of padding after its first field.
    let container = Container {
        first: HLAoctet(0xaa),
        inner: BooleanOctetFloat { flag: HLAboolean(true), octet: HLAoctet(0xbb), value: HLAfloat64BE(1.0) },
    };
    let mut expected = vec![0xaa, 0, 0, 0, 0, 0, 0, 0]; // first, padding to 8
    expected.extend([0, 0, 0, 1, 0xbb, 0, 0, 0]); // flag, octet, padding to 8
    expected.extend([0x3f, 0xf0, 0, 0, 0, 0, 0, 0]); // value
    check(container, &expected);
}

/// Padding octets are written as zeros (4.14.10 asks them of the sender); the clause says nothing of a
/// receiver that finds other octets there, and the typed layer and the dynamic containers ignore them:
/// the value is the one the same octets give with zero padding, and it encodes back with zeros.
#[test]
fn non_zero_padding_is_ignored() {
    let zero = [1, 0, 0, 0, 0, 0, 0, 2];
    let value = OctetThenInteger { octet: HLAoctet(1), integer: HLAinteger32BE(2) };
    let other = [1, 0xaa, 0xbb, 0xcc, 0, 0, 0, 2];
    assert_eq!(decode_from_slice_strict::<OctetThenInteger>(&other), Ok(value.clone()));
    assert_eq!(encode_to_vec(&value), zero);
    // After the count of a variable array of 64-bit elements.
    let floats = [0, 0, 0, 1, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0];
    assert_eq!(decode_from_slice_strict::<Vec<HLAfloat64BE>>(&floats), Ok(vec![HLAfloat64BE(1.0)]));
    // Between the elements of a fixed array (the example of 4.14.10.4).
    let mut pairs = EXAMPLE_4_OCTETS;
    pairs[5..8].copy_from_slice(&[0xee, 0xee, 0xee]);
    assert_eq!(
        decode_from_slice_strict::<[IntegerThenOctet; 2]>(&pairs),
        decode_from_slice_strict::<[IntegerThenOctet; 2]>(&EXAMPLE_4_OCTETS)
    );
    assert!(decode_from_slice_strict::<[IntegerThenOctet; 2]>(&pairs).is_ok());
    // After the discriminant of a variant record.
    let variant = [2, 1, 2, 3, 4, 5, 6, 7, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0];
    assert_eq!(
        decode_from_slice_strict::<OctetOrFloat>(&variant),
        Ok(OctetOrFloat::Float(HLAfloat64BE(1.0)))
    );

    let mut dynamic = HLAfixedRecord::new().with(HLAoctet(0)).with(HLAinteger32BE(0));
    dynamic.decode_slice_strict(&other).unwrap();
    assert_eq!(dynamic.get_as::<HLAoctet>(0), Some(&HLAoctet(1)));
    assert_eq!(dynamic.get_as::<HLAinteger32BE>(1), Some(&HLAinteger32BE(2)));
    assert_eq!(dynamic.to_bytes(), Ok(zero.to_vec()));
}

/// The same rules through the FOM codec.
#[cfg(feature = "fom")]
#[test]
fn constructed_types_in_the_fom_codec_follow_4_14_10() {
    let codec = Tables::default()
        .record(
            "BooleanOctetFloat",
            &[("Flag", "HLAboolean"), ("Octet", "HLAoctet"), ("Value", "HLAfloat64BE")],
        )
        .record("Container", &[("First", "HLAoctet"), ("Inner", "BooleanOctetFloat")])
        .record("OctetThenInteger", &[("Octet", "HLAoctet"), ("Integer", "HLAinteger32BE")])
        .codec();
    assert_eq!(codec.octet_boundary("BooleanOctetFloat"), Some(8));
    assert_eq!(codec.octet_boundary("Container"), Some(8));
    let inner = Value::record([
        ("Flag", Value::Bool(true)),
        ("Octet", Value::Octet(0xbb)),
        ("Value", Value::from(1.0)),
    ]);
    let container = Value::record([("First", Value::Octet(0xaa)), ("Inner", inner)]);
    let mut expected = vec![0xaa, 0, 0, 0, 0, 0, 0, 0];
    expected.extend([0, 0, 0, 1, 0xbb, 0, 0, 0]);
    expected.extend([0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);
    both_ways(&codec, "Container", &container, &expected);

    // Padding that is not zero is ignored when decoding; encoding writes zeros again.
    let mut other = expected.clone();
    other[1..8].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7]);
    other[13..16].copy_from_slice(&[0xff, 0xff, 0xff]);
    assert_eq!(codec.decode("Container", &other).as_ref(), Ok(&container));
    let pair = Value::record([("Octet", Value::Octet(1)), ("Integer", Value::from(2))]);
    assert_eq!(codec.decode("OctetThenInteger", &[1, 9, 9, 9, 0, 0, 0, 2]).as_ref(), Ok(&pair));
    assert_eq!(codec.encode("OctetThenInteger", &pair), Ok(vec![1, 0, 0, 0, 0, 0, 0, 2]));
}

/// The MOM goes through the FOM codec: an attribute handle list whose first handle of one octet is
/// followed by padding that is not zero decodes as the same list with zero padding.
#[cfg(feature = "fom")]
#[test]
fn non_zero_padding_in_a_mom_value_is_ignored() {
    let codec = mim();
    let zero = [0, 0, 0, 2, 0, 0, 0, 1, 7, 0, 0, 0, 0, 0, 0, 1, 8];
    let other = [0, 0, 0, 2, 0, 0, 0, 1, 7, 0xaa, 0xbb, 0xcc, 0, 0, 0, 1, 8];
    let list = Value::array([Value::handle([7u8]), Value::handle([8u8])]);
    both_ways(&codec, "HLAattributeHandleList", &list, &zero);
    assert_eq!(codec.decode("HLAattributeHandleList", &other), Ok(list));
}

// ---------------------------------------------------------------------------------------------------
// 4.14.10.1: HLAfixedRecord
// ---------------------------------------------------------------------------------------------------

hla_fixed_record! {
    /// The example of 4.14.10.1.
    struct OctetBooleanFloat {
        octet: HLAoctet,
        flag: HLAboolean,
        value: HLAfloat64BE,
    }
}

hla_fixed_record! {
    /// The same components in the reverse order.
    struct FloatBooleanOctet {
        value: HLAfloat64BE,
        flag: HLAboolean,
        octet: HLAoctet,
    }
}

/// Equation (1): P1 = 3 since (0 + 1 + P1) mod 4 = 0, P2 = 0 since (4 + 4 + P2) mod 8 = 0; 16 octets.
fn octet_boolean_float_octets() -> Vec<u8> {
    let mut octets = vec![0xab, 0, 0, 0]; // HLAoctet, 3 octets of padding
    octets.extend([0, 0, 0, 1]); // HLAboolean
    octets.extend([0xc0, 0x04, 0, 0, 0, 0, 0, 0]); // HLAfloat64BE -2.5
    octets
}

/// In the reverse order no component needs padding: 13 octets, nothing after the last one.
fn float_boolean_octet_octets() -> Vec<u8> {
    let mut octets = vec![0xc0, 0x04, 0, 0, 0, 0, 0, 0];
    octets.extend([0, 0, 0, 1]);
    octets.push(0xab);
    octets
}

/// The example of 4.14.10.1 in the typed layer and the dynamic container.
#[test]
fn fixed_record_example_of_4_14_10_1() {
    let forward =
        OctetBooleanFloat { octet: HLAoctet(0xab), flag: HLAboolean(true), value: HLAfloat64BE(-2.5) };
    check(forward, &octet_boolean_float_octets());
    let reverse =
        FloatBooleanOctet { value: HLAfloat64BE(-2.5), flag: HLAboolean(true), octet: HLAoctet(0xab) };
    check(reverse, &float_boolean_octet_octets());

    let dynamic = HLAfixedRecord::new().with(HLAoctet(0xab)).with(HLAboolean(true)).with(HLAfloat64BE(-2.5));
    let blank = HLAfixedRecord::new().with(HLAoctet(0)).with(HLAboolean(false)).with(HLAfloat64BE(0.0));
    check_dynamic(&dynamic, blank, &octet_boolean_float_octets());
    let dynamic = HLAfixedRecord::new().with(HLAfloat64BE(-2.5)).with(HLAboolean(true)).with(HLAoctet(0xab));
    let blank = HLAfixedRecord::new().with(HLAfloat64BE(0.0)).with(HLAboolean(false)).with(HLAoctet(0));
    check_dynamic(&dynamic, blank, &float_boolean_octet_octets());

    // The padding of equation (1) is part of the encoding: without it the boolean is read from the wrong
    // octets, and the record is three octets short.
    assert!(matches!(
        decode_from_slice::<OctetBooleanFloat>(&[0xab, 0, 0, 0, 1, 0xc0, 0x04, 0, 0, 0, 0, 0, 0]),
        Err(DecoderError::InvalidValue { type_name: "HLAboolean", .. })
    ));
    assert!(matches!(
        decode_from_slice::<OctetBooleanFloat>(&octet_boolean_float_octets()[..13]),
        Err(DecoderError::Truncated { offset: 8, needed: 8, remaining: 5 })
    ));
}

/// The example of 4.14.10.1 through the FOM codec.
#[cfg(feature = "fom")]
#[test]
fn fixed_record_example_of_4_14_10_1_in_the_fom_codec() {
    let codec = Tables::default()
        .record("Forward", &[("A", "HLAoctet"), ("B", "HLAboolean"), ("C", "HLAfloat64BE")])
        .record("Reverse", &[("C", "HLAfloat64BE"), ("B", "HLAboolean"), ("A", "HLAoctet")])
        .codec();
    let forward =
        Value::record([("A", Value::Octet(0xab)), ("B", Value::Bool(true)), ("C", Value::from(-2.5))]);
    both_ways(&codec, "Forward", &forward, &octet_boolean_float_octets());
    let reverse =
        Value::record([("C", Value::from(-2.5)), ("B", Value::Bool(true)), ("A", Value::Octet(0xab))]);
    both_ways(&codec, "Reverse", &reverse, &float_boolean_octet_octets());
}

// ---------------------------------------------------------------------------------------------------
// 4.14.10.2: HLAvariantRecord
// ---------------------------------------------------------------------------------------------------

hla_fixed_record! {
    #[derive(Default)]
    struct TwoOctets {
        first: HLAoctet,
        second: HLAoctet,
    }
}

hla_variant_record! {
    /// The example of 4.14.10.2, with a third enumerator that has no alternative.
    enum Example2: HLAoctet {
        Integer(HLAinteger32BE) = HLAoctet(1),
        Pair(TwoOctets) = HLAoctet(2),
        Nothing = HLAoctet(3),
    }
}

/// Equation (2): V is the largest octet boundary of the alternatives, 4, so P = 3 whichever alternative is
/// active; nothing after the discriminant when no alternative applies, nothing after the alternative.
#[test]
fn variant_record_example_of_4_14_10_2() {
    check(Example2::Integer(HLAinteger32BE(0x0102_0304)), &[1, 0, 0, 0, 1, 2, 3, 4]);
    check(Example2::Pair(TwoOctets { first: HLAoctet(5), second: HLAoctet(6) }), &[2, 0, 0, 0, 5, 6]);
    check(Example2::Nothing, &[3]);
    assert_eq!(Example2::OCTET_BOUNDARY, 4);
    assert_eq!(
        decode_from_slice_strict::<Example2>(&[2, 0, 0, 1, 5, 6]),
        Ok(Example2::Pair(TwoOctets { first: HLAoctet(5), second: HLAoctet(6) }))
    );

    let mut dynamic = HLAvariantRecord::new(HLAoctet(0));
    dynamic.set_variant(HLAoctet(1), HLAinteger32BE(0x0102_0304)).unwrap();
    dynamic.set_variant(HLAoctet(2), HLAfixedRecord::new().with(HLAoctet(5)).with(HLAoctet(6))).unwrap();
    dynamic.set_empty_variant(HLAoctet(3)).unwrap();
    let blank = || {
        let mut blank = HLAvariantRecord::new(HLAoctet(0));
        blank.set_variant(HLAoctet(1), HLAinteger32BE(0)).unwrap();
        blank.set_variant(HLAoctet(2), HLAfixedRecord::new().with(HLAoctet(0)).with(HLAoctet(0))).unwrap();
        blank.set_empty_variant(HLAoctet(3)).unwrap();
        blank
    };
    check_dynamic(&dynamic, blank(), &[3]);
    dynamic.set_discriminant(HLAoctet(2)).unwrap();
    check_dynamic(&dynamic, blank(), &[2, 0, 0, 0, 5, 6]);
    dynamic.set_discriminant(HLAoctet(1)).unwrap();
    check_dynamic(&dynamic, blank(), &[1, 0, 0, 0, 1, 2, 3, 4]);
}

/// The same through the FOM codec. An enumerator that no alternative names, without HLAother, is
/// encoded as the discriminant alone; inside a record, the next field follows it directly.
#[cfg(feature = "fom")]
#[test]
fn variant_record_example_of_4_14_10_2_in_the_fom_codec() {
    let codec = Tables::default()
        .enumerated("Choice", "HLAoctet", &[("I", &[1]), ("P", &[2]), ("N", &[3])])
        .record("TwoOctets", &[("First", "HLAoctet"), ("Second", "HLAoctet")])
        .variant(
            "Example",
            "HLAvariantRecord",
            "Choice",
            &[("I", "Integer", "HLAinteger32BE"), ("P", "Pair", "TwoOctets")],
        )
        .record("Framed", &[("Variant", "Example"), ("Tail", "HLAoctet")])
        .codec();
    assert_eq!(codec.octet_boundary("Example"), Some(4));
    let integer = Value::variant_named(Enumerator::new("I", 1), "Integer", 0x0102_0304);
    both_ways(&codec, "Example", &integer, &[1, 0, 0, 0, 1, 2, 3, 4]);
    let pair = Value::record([("First", Value::Octet(5)), ("Second", Value::Octet(6))]);
    let pair = Value::variant_named(Enumerator::new("P", 2), "Pair", pair);
    both_ways(&codec, "Example", &pair, &[2, 0, 0, 0, 5, 6]);
    let nothing = Value::variant(Enumerator::new("N", 3), None);
    both_ways(&codec, "Example", &nothing, &[3]);
    assert_eq!(codec.encode("Example", &Value::variant("N", None)), Ok(vec![3]));

    let framed = |variant: Value| Value::record([("Variant", variant), ("Tail", Value::Octet(9))]);
    both_ways(&codec, "Framed", &framed(nothing.clone()), &[3, 9]);
    both_ways(&codec, "Framed", &framed(pair), &[2, 0, 0, 0, 5, 6, 9]);

    // An enumerator without alternative carries no value.
    let error = codec.encode("Example", &Value::variant("N", Some(Value::Octet(1)))).unwrap_err();
    assert!(matches!(error.reason(), Some(Reason::Alternative { .. })), "{error}");
    // A number that no enumerator has here: another module may have added it to Choice (annex C), and as
    // every module gives an HLAvariantRecord the same alternatives (4.14.8), none applies to it: the
    // discriminant alone, decoded and passed on.
    let unknown = Value::variant(Enumerator::numbered(4), None);
    both_ways(&codec, "Example", &unknown, &[4]);
    both_ways(&codec, "Framed", &framed(unknown), &[4, 9]);
    let error =
        codec.encode("Example", &Value::variant(Enumerator::numbered(4), Some(Value::Octet(1)))).unwrap_err();
    assert!(matches!(error.reason(), Some(Reason::Alternative { .. })), "{error}");
}

/// With HLAother, a number that no enumerator has here takes the HLAother alternative: in the merged FOM
/// of the federation, HLAother covers the enumerators that other modules add.
#[cfg(feature = "fom")]
#[test]
fn variant_record_hlaother_covers_unknown_enumerators() {
    let codec = Tables::default()
        .enumerated("Choice", "HLAoctet", &[("I", &[1]), ("N", &[3])])
        .variant(
            "WithOther",
            "HLAvariantRecord",
            "Choice",
            &[("I", "Integer", "HLAinteger32BE"), ("HLAother", "Rest", "HLAoctet")],
        )
        .codec();
    let rest = Value::variant_named(Enumerator::numbered(7), "Rest", Value::Octet(5));
    both_ways(&codec, "WithOther", &rest, &[7, 0, 0, 0, 5]);
    let known = Value::variant_named(Enumerator::new("N", 3), "Rest", Value::Octet(5));
    both_ways(&codec, "WithOther", &known, &[3, 0, 0, 0, 5]);
}

// ---------------------------------------------------------------------------------------------------
// 4.14.10.3: HLAextendableVariantRecord
// ---------------------------------------------------------------------------------------------------

hla_extendable_variant_record! {
    /// The example of 4.14.10.3: an HLAoctet discriminant, an HLAfloat32LE and a record of two octets.
    enum Example3: HLAoctet {
        Float(HLAfloat32LE) = HLAoctet(1),
        Pair(TwoOctets) = HLAoctet(2),
        Nothing = HLAoctet(3),
    }
}

hla_extendable_variant_record! {
    /// A 64-bit discriminant: the length field ends at offset 12, so equation (4) asks for 4 octets.
    enum Wide: HLAinteger64BE {
        Short(HLAinteger16BE) = HLAinteger64BE(1),
        Token(HLAtoken) = HLAinteger64BE(2),
        Nothing = HLAinteger64BE(3),
    }
}

hla_extendable_variant_record! {
    /// A 16-bit discriminant: equation (3) asks for 2 octets, equation (4) for none.
    enum Narrow: HLAinteger16BE {
        Float(HLAfloat64BE) = HLAinteger16BE(1),
    }
}

hla_fixed_record! {
    struct WideThenOctet {
        wide: Wide,
        octet: HLAoctet,
    }
}

hla_fixed_record! {
    struct WideThenInteger {
        wide: Wide,
        integer: HLAinteger32BE,
    }
}

hla_fixed_record! {
    struct Framed3 {
        head: HLAoctet,
        body: Example3,
        tail: HLAoctet,
    }
}

/// The two layouts drawn in 4.14.10.3. Equation (3): (1 + P) mod 4 = 0, P = 3; equation (4):
/// (8 + P) mod 8 = 0, P = 0; encoded_length counts the alternative only.
#[test]
fn extendable_variant_record_example_of_4_14_10_3() {
    check(Example3::Float(HLAfloat32LE(-2.5)), &[1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0x20, 0xc0]);
    check(
        Example3::Pair(TwoOctets { first: HLAoctet(5), second: HLAoctet(6) }),
        &[2, 0, 0, 0, 0, 0, 0, 2, 5, 6],
    );
    // No alternative applies: encoded_length 0.
    check(Example3::Nothing, &[3, 0, 0, 0, 0, 0, 0, 0]);
    // The record has the octet boundary 8 whatever its alternatives, and nothing follows the alternative.
    assert_eq!(Example3::OCTET_BOUNDARY, 8);
    assert_eq!(Example3::ALTERNATIVE_BOUNDARY, 4);
    let framed =
        Framed3 { head: HLAoctet(0xaa), body: Example3::Pair(TwoOctets::default()), tail: HLAoctet(0xbb) };
    check(framed, &[0xaa, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0xbb]);

    let mut dynamic = HLAextendableVariantRecord::new(HLAoctet(0));
    dynamic.set_variant(HLAoctet(2), HLAfixedRecord::new().with(HLAoctet(5)).with(HLAoctet(6))).unwrap();
    dynamic.set_variant(HLAoctet(1), HLAfloat32LE(-2.5)).unwrap();
    let blank = || {
        let mut blank = HLAextendableVariantRecord::new(HLAoctet(0));
        blank.set_variant(HLAoctet(1), HLAfloat32LE(0.0)).unwrap();
        blank.set_variant(HLAoctet(2), HLAfixedRecord::new().with(HLAoctet(0)).with(HLAoctet(0))).unwrap();
        blank
    };
    check_dynamic(&dynamic, blank(), &[1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0x20, 0xc0]);
    dynamic.set_discriminant(HLAoctet(2)).unwrap();
    check_dynamic(&dynamic, blank(), &[2, 0, 0, 0, 0, 0, 0, 2, 5, 6]);
}

/// Discriminants of other sizes. Equation (4) does not depend on the presence of an alternative: after a
/// 64-bit discriminant the four octets of padding are there also when the alternative is empty or when
/// none applies.
#[test]
fn extendable_padding_after_the_length_field() {
    let wide_head = [0, 0, 0, 0, 0, 0, 0];
    let with = |discriminant: u8, rest: &[u8]| {
        let mut octets = wide_head.to_vec();
        octets.push(discriminant);
        octets.extend(rest);
        octets
    };
    check(Wide::Short(HLAinteger16BE(7)), &with(1, &[0, 0, 0, 2, 0, 0, 0, 0, 0, 7]));
    check(Wide::Token([]), &with(2, &[0, 0, 0, 0, 0, 0, 0, 0]));
    check(Wide::Nothing, &with(3, &[0, 0, 0, 0, 0, 0, 0, 0]));
    // An unknown alternative is skipped over the same padding.
    let unknown = with(9, &[0, 0, 0, 3, 0, 0, 0, 0, 1, 2, 3]);
    let skipped = Wide::Unknown { discriminant: HLAinteger64BE(9), data: vec![1, 2, 3] };
    assert_eq!(decode_from_slice_strict::<Wide>(&unknown), Ok(skipped.clone()));
    assert_eq!(encode_to_vec(&skipped), unknown);
    let empty = with(9, &[0, 0, 0, 0, 0, 0, 0, 0]);
    assert_eq!(
        decode_from_slice_strict::<Wide>(&empty),
        Ok(Wide::Unknown { discriminant: HLAinteger64BE(9), data: vec![] })
    );
    // The form without that padding (MicroRTI 0.1.2) is still read where it cannot be the padded form:
    // at the end of the input, or followed by fewer octets than the padding.
    assert_eq!(decode_from_slice_strict::<Wide>(&with(3, &[0, 0, 0, 0])), Ok(Wide::Nothing));
    let old_framed = with(3, &[0, 0, 0, 0, 0xbb]);
    let framed = WideThenOctet { wide: Wide::Nothing, octet: HLAoctet(0xbb) };
    assert_eq!(decode_from_slice_strict::<WideThenOctet>(&old_framed), Ok(framed.clone()));
    check(framed, &with(3, &[0, 0, 0, 0, 0, 0, 0, 0, 0xbb]));
    // Followed by four octets or more, they are read as the padding of the current form: here the
    // 0.1.2 octets of an integer that follows, which then lacks its own octets.
    let old_then_integer = with(3, &[0, 0, 0, 0, 0, 0, 0, 7]);
    assert!(matches!(
        decode_from_slice_strict::<WideThenInteger>(&old_then_integer),
        Err(DecoderError::Truncated { .. })
    ));
    let mut dynamic = HLAextendableVariantRecord::new(HLAinteger64BE(0));
    dynamic.set_empty_variant(HLAinteger64BE(3)).unwrap();
    dynamic.decode_slice_strict(&with(3, &[0, 0, 0, 0])).unwrap();
    assert_eq!(dynamic.to_bytes(), Ok(with(3, &[0, 0, 0, 0, 0, 0, 0, 0])));

    check(Narrow::Float(HLAfloat64BE(1.0)), &[0, 1, 0, 0, 0, 0, 0, 8, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);

    let mut dynamic = HLAextendableVariantRecord::new(HLAinteger64BE(0));
    dynamic.set_empty_variant(HLAinteger64BE(3)).unwrap();
    assert_eq!(dynamic.to_bytes(), Ok(with(3, &[0, 0, 0, 0, 0, 0, 0, 0])));
}

/// Encoded_length is an HLAinteger32BE: a negative length is refused, and no alternative longer
/// than `i32::MAX` octets can be encoded. A length that the alternative does not fill exactly is refused
/// too; the clause says nothing of a receiver that meets one.
#[test]
fn extendable_length_field() {
    let negative = [1, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0x20, 0xc0];
    assert!(matches!(
        decode_from_slice::<Example3>(&negative),
        Err(DecoderError::InvalidValue { type_name: "HLAextendableVariantRecord", .. })
    ));
    let mut dynamic = HLAextendableVariantRecord::new(HLAoctet(0));
    dynamic.set_variant(HLAoctet(1), HLAfloat32LE(0.0)).unwrap();
    assert!(matches!(dynamic.decode_slice(&negative), Err(DecoderError::InvalidValue { .. })));

    let mut counter = ByteWriter::counter();
    extendable::write_length(&mut counter, i32::MAX as usize);
    assert_eq!(counter.status(), Ok(()));
    let mut counter = ByteWriter::counter();
    extendable::write_length(&mut counter, i32::MAX as usize + 1);
    assert_eq!(counter.status(), Err(EncoderError::AlternativeTooLong { length: i32::MAX as usize + 1 }));

    // A known alternative must use exactly the announced length.
    assert_eq!(
        decode_from_slice::<Example3>(&[1, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0x20, 0xc0, 0]),
        Err(DecoderError::LengthMismatch { declared: 5, consumed: 4 })
    );
    assert_eq!(
        dynamic.decode_slice(&[1, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0x20, 0xc0, 0]),
        Err(DecoderError::LengthMismatch { declared: 5, consumed: 4 })
    );
}

/// An enumerator declared without data may receive data, because another FOM module can give it
/// an alternative (annex C merges the alternatives of an HLAextendableVariantRecord): the octets are
/// passed on, like those of an unknown enumerator.
#[test]
fn extendable_alternatives_added_by_other_modules() {
    let extended = [3, 0, 0, 0, 0, 0, 0, 2, 7, 8];
    let passed = Example3::Unknown { discriminant: HLAoctet(3), data: vec![7, 8] };
    assert_eq!(decode_from_slice_strict::<Example3>(&extended), Ok(passed.clone()));
    assert_eq!(encode_to_vec(&passed), extended);

    let mut dynamic = HLAextendableVariantRecord::new(HLAoctet(0));
    dynamic.set_empty_variant(HLAoctet(3)).unwrap();
    dynamic.decode_slice_strict(&extended).unwrap();
    assert_eq!(dynamic.unknown_alternative(), Some(&[7u8, 8][..]));
    assert_eq!(dynamic.to_bytes(), Ok(extended.to_vec()));
    // Choosing the discriminant again forgets the octets.
    dynamic.set_discriminant(HLAoctet(3)).unwrap();
    assert_eq!(dynamic.to_bytes(), Ok(vec![3, 0, 0, 0, 0, 0, 0, 0]));
}

/// The same in the FOM codec, for an enumerator that a row without data names and for one that no row
/// names: the octets are kept as raw data and passed on, as in the typed layer and the dynamic container.
#[cfg(feature = "fom")]
#[test]
fn extendable_alternatives_added_by_other_modules_in_the_fom_codec() {
    let codec = Tables::default()
        .enumerated("Choice", "HLAoctet", &[("F", &[1]), ("P", &[2]), ("N", &[3]), ("Q", &[4])])
        .variant(
            "Open",
            "HLAextendableVariantRecord",
            "Choice",
            &[("F", "Float", "HLAfloat32LE"), ("N", "", "")],
        )
        .codec();
    let extended = [3, 0, 0, 0, 0, 0, 0, 2, 7, 8];
    let passed = Value::variant(Enumerator::new("N", 3), Some(Value::raw([7u8, 8])));
    both_ways(&codec, "Open", &passed, &extended);
    let plain = Value::variant(Enumerator::new("N", 3), None);
    both_ways(&codec, "Open", &plain, &[3, 0, 0, 0, 0, 0, 0, 0]);
    let unnamed = Value::variant(Enumerator::new("Q", 4), Some(Value::raw([7u8, 8])));
    both_ways(&codec, "Open", &unnamed, &[4, 0, 0, 0, 0, 0, 0, 2, 7, 8]);
    // Only raw octets can be passed on.
    let typed = Value::variant(Enumerator::new("N", 3), Some(Value::from(1)));
    assert!(matches!(codec.encode("Open", &typed).unwrap_err().reason(), Some(Reason::Alternative { .. })));

    // The three layers agree on these octets.
    assert_eq!(
        decode_from_slice_strict::<Example3>(&extended),
        Ok(Example3::Unknown { discriminant: HLAoctet(3), data: vec![7, 8] })
    );
    let mut dynamic = HLAextendableVariantRecord::new(HLAoctet(0));
    dynamic.set_empty_variant(HLAoctet(3)).unwrap();
    dynamic.decode_slice_strict(&extended).unwrap();
    assert_eq!(dynamic.unknown_alternative(), Some(&[7u8, 8][..]));
}

/// A data element of octet boundary 16, which no predefined representation has.
#[derive(Debug, Clone, PartialEq, Default)]
struct Aligned16(u8);

impl Encode for Aligned16 {
    const OCTET_BOUNDARY: usize = 16;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        writer.align(16);
        writer.put_u8(self.0);
    }
}

impl Decode for Aligned16 {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        reader.align(16)?;
        reader.read_u8().map(Self)
    }
}

/// An alternative whose octet boundary exceeds 8 cannot use HLAextendableVariantRecord.
#[test]
fn extendable_alternatives_above_boundary_8_are_refused() {
    let mut dynamic = HLAextendableVariantRecord::new(HLAoctet(0));
    dynamic.set_variant(HLAoctet(1), Aligned16(1)).unwrap();
    assert!(matches!(dynamic.to_bytes(), Err(EncoderError::TypeMismatch { .. })));
}

/// The same rules through the FOM codec.
#[cfg(feature = "fom")]
#[test]
fn extendable_variant_records_in_the_fom_codec() {
    let codec = Tables::default()
        .basic("Wide128", 128, "128-bit value", "Big")
        .enumerated("Choice", "HLAoctet", &[("F", &[1]), ("P", &[2]), ("N", &[3])])
        .enumerated("WideChoice", "HLAinteger64BE", &[("S", &[1]), ("N", &[3])])
        .record("TwoOctets", &[("First", "HLAoctet"), ("Second", "HLAoctet")])
        .variant(
            "Example",
            "HLAextendableVariantRecord",
            "Choice",
            &[("F", "Float", "HLAfloat32LE"), ("P", "Pair", "TwoOctets")],
        )
        .variant(
            "WideExample",
            "HLAextendableVariantRecord",
            "WideChoice",
            &[("S", "Short", "HLAinteger16BE")],
        )
        .variant("TooWide", "HLAextendableVariantRecord", "Choice", &[("F", "Big", "Wide128")])
        .codec();
    assert_eq!(codec.octet_boundary("Example"), Some(8));
    let float = Value::variant_named(Enumerator::new("F", 1), "Float", -2.5);
    both_ways(&codec, "Example", &float, &[1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0x20, 0xc0]);
    let pair = Value::record([("First", Value::Octet(5)), ("Second", Value::Octet(6))]);
    let pair = Value::variant_named(Enumerator::new("P", 2), "Pair", pair);
    both_ways(&codec, "Example", &pair, &[2, 0, 0, 0, 0, 0, 0, 2, 5, 6]);
    let nothing = Value::variant(Enumerator::new("N", 3), None);
    both_ways(&codec, "Example", &nothing, &[3, 0, 0, 0, 0, 0, 0, 0]);
    // Data for an enumerator without alternative here: passed on as raw octets.
    let extended = Value::variant(Enumerator::new("N", 3), Some(Value::raw([7u8, 8])));
    both_ways(&codec, "Example", &extended, &[3, 0, 0, 0, 0, 0, 0, 2, 7, 8]);

    let mut wide = vec![0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7];
    let short = Value::variant_named(Enumerator::new("S", 1), "Short", 7);
    both_ways(&codec, "WideExample", &short, &wide);
    wide.truncate(16);
    wide[7] = 3;
    wide[11] = 0;
    let none = Value::variant(Enumerator::new("N", 3), None);
    both_ways(&codec, "WideExample", &none, &wide);
    // The 0.1.2 form, without the padding, at the end of the input.
    assert_eq!(codec.decode("WideExample", &wide[..12]), Ok(none));

    let error = codec.decode("Example", &[1, 0, 0, 0, 0xff, 0xff, 0xff, 0xfc, 0, 0, 0x20, 0xc0]).unwrap_err();
    assert!(matches!(error.reason(), Some(Reason::Decoder(DecoderError::InvalidValue { .. }))), "{error}");
    let error = codec.decode("Example", &[1, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0x20, 0xc0, 0]).unwrap_err();
    assert_eq!(
        error.reason(),
        Some(&Reason::Decoder(DecoderError::LengthMismatch { declared: 5, consumed: 4 }))
    );

    assert!(codec.raw_reason("TooWide").is_some_and(|reason| reason.contains("octet boundary 16")));
}

// ---------------------------------------------------------------------------------------------------
// 4.14.10.4: HLAfixedArray
// ---------------------------------------------------------------------------------------------------

hla_fixed_record! {
    /// The element of the example of 4.14.10.4: 5 octets, octet boundary 4.
    #[derive(Default)]
    struct IntegerThenOctet {
        integer: HLAinteger32BE,
        octet: HLAoctet,
    }
}

/// Equation (5): (5 + P) mod 4 = 0, P = 3 after every element but the last; 13 octets for two.
const EXAMPLE_4_OCTETS: [u8; 13] = [0, 0, 0, 1, 0xa1, 0, 0, 0, 0, 0, 0, 2, 0xa2];

/// The example of 4.14.10.4 in the typed layer and the dynamic container.
#[test]
fn fixed_array_example_of_4_14_10_4() {
    let array = [
        IntegerThenOctet { integer: HLAinteger32BE(1), octet: HLAoctet(0xa1) },
        IntegerThenOctet { integer: HLAinteger32BE(2), octet: HLAoctet(0xa2) },
    ];
    check(array, &EXAMPLE_4_OCTETS);
    assert_eq!(<[IntegerThenOctet; 2]>::OCTET_BOUNDARY, 4);
    // With elements of octet boundary 8 (13 octets each, 4.14.10.1): 3 octets of padding as well.
    let reverse =
        FloatBooleanOctet { value: HLAfloat64BE(-2.5), flag: HLAboolean(true), octet: HLAoctet(0xab) };
    let mut expected = float_boolean_octet_octets();
    expected.extend([0, 0, 0]);
    expected.extend(float_boolean_octet_octets());
    check([reverse.clone(), reverse], &expected);

    let element =
        |integer: i32, octet: u8| HLAfixedRecord::new().with(HLAinteger32BE(integer)).with(HLAoctet(octet));
    let dynamic = HLAfixedArray::from_elements(element(0, 0), [element(1, 0xa1), element(2, 0xa2)]).unwrap();
    check_dynamic(&dynamic, HLAfixedArray::new(element(0, 0), 2), &EXAMPLE_4_OCTETS);
}

/// The same through the FOM codec.
#[cfg(feature = "fom")]
#[test]
fn fixed_array_example_of_4_14_10_4_in_the_fom_codec() {
    let codec = Tables::default()
        .record("IntegerThenOctet", &[("Integer", "HLAinteger32BE"), ("Octet", "HLAoctet")])
        .array("Pairs", "IntegerThenOctet", "2", "HLAfixedArray")
        .codec();
    let element = |integer: i32, octet: u8| {
        Value::record([("Integer", Value::from(integer)), ("Octet", Value::Octet(octet))])
    };
    both_ways(&codec, "Pairs", &Value::array([element(1, 0xa1), element(2, 0xa2)]), &EXAMPLE_4_OCTETS);
    assert_eq!(codec.octet_boundary("Pairs"), Some(4));
}

// ---------------------------------------------------------------------------------------------------
// 4.14.10.5: HLAvariableArray
// ---------------------------------------------------------------------------------------------------

/// A 24-bit big-endian value: three octets, octet boundary 4 (4.14.10), as in the examples of 4.14.10.5.
#[derive(Debug, Clone, PartialEq, Default)]
struct U24(u32);

impl Encode for U24 {
    const OCTET_BOUNDARY: usize = 4;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        writer.align(4);
        writer.put_slice(&self.0.to_be_bytes()[1..]);
    }
}

impl Decode for U24 {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        reader.align(4)?;
        let [a, b, c] = reader.take_array::<3>()?;
        Ok(Self(u32::from_be_bytes([0, a, b, c])))
    }
}

/// First example: equation (6) with V = max(8, 4) = 8 gives 4 octets of padding after the count.
const FLOATS_OCTETS: [u8; 16] = [0, 0, 0, 1, 0, 0, 0, 0, 0xc0, 0x04, 0, 0, 0, 0, 0, 0];
/// Second example: V = 4, no padding after the count, 1 octet after each 24-bit element but the last.
const VAR_ARRAY_OCTETS: [u8; 11] = [0, 0, 0, 2, 0x01, 0x02, 0x03, 0, 0x04, 0x05, 0x06];
/// Third example: an array of two such arrays, of one and two elements: 23 octets. The first inner array
/// takes 7 octets, so 1 octet of padding follows it.
const NESTED_OCTETS: [u8; 23] = [
    0, 0, 0, 2, // outer count
    0, 0, 0, 1, 0x01, 0x02, 0x03, 0, // first inner array, padding
    0, 0, 0, 2, 0x04, 0x05, 0x06, 0, 0x07, 0x08, 0x09, // second inner array
];

/// The three examples of 4.14.10.5 in the typed layer and the dynamic container.
#[test]
fn variable_array_examples_of_4_14_10_5() {
    check(vec![HLAfloat64BE(-2.5)], &FLOATS_OCTETS);
    check(vec![U24(0x01_0203), U24(0x04_0506)], &VAR_ARRAY_OCTETS);
    check(vec![vec![U24(0x01_0203)], vec![U24(0x04_0506), U24(0x07_0809)]], &NESTED_OCTETS);
    assert_eq!(<Vec<HLAfloat64BE>>::OCTET_BOUNDARY, 8);
    assert_eq!(<Vec<U24>>::OCTET_BOUNDARY, 4);
    assert_eq!(<Vec<Vec<U24>>>::OCTET_BOUNDARY, 4);
    // An empty array is its count alone.
    check(Vec::<HLAfloat64BE>::new(), &[0, 0, 0, 0]);

    let dynamic = HLAvariableArray::from_elements(HLAfloat64BE(0.0), [HLAfloat64BE(-2.5)]).unwrap();
    check_dynamic(&dynamic, HLAvariableArray::new(HLAfloat64BE(0.0)), &FLOATS_OCTETS);
    let inner = |values: &[u32]| {
        HLAvariableArray::from_elements(U24(0), values.iter().map(|&value| U24(value))).unwrap()
    };
    let nested =
        HLAvariableArray::from_elements(inner(&[]), [inner(&[0x01_0203]), inner(&[0x04_0506, 0x07_0809])])
            .unwrap();
    check_dynamic(&nested, HLAvariableArray::new(inner(&[])), &NESTED_OCTETS);

    // The count is an HLAinteger32BE: a negative one is refused.
    assert_eq!(
        decode_from_slice::<Vec<HLAoctet>>(&[0xff, 0xff, 0xff, 0xff]),
        Err(DecoderError::InvalidCount { count: -1 })
    );
    let mut blank = HLAvariableArray::new(HLAoctet(0));
    assert_eq!(blank.decode_slice(&[0x80, 0, 0, 0]), Err(DecoderError::InvalidCount { count: i32::MIN }));
}

/// The same through the FOM codec, with a real 24-bit basic representation.
#[cfg(feature = "fom")]
#[test]
fn variable_array_examples_of_4_14_10_5_in_the_fom_codec() {
    let codec = Tables::default()
        .basic("U24", 24, "Integer in the range [0, 2^24 - 1]", "Big")
        .array("Floats", "HLAfloat64BE", "Dynamic", "HLAvariableArray")
        .array("VarArray", "U24", "Dynamic", "HLAvariableArray")
        .array("VarArrays", "VarArray", "Dynamic", "HLAvariableArray")
        .codec();
    both_ways(&codec, "Floats", &Value::array([-2.5]), &FLOATS_OCTETS);
    both_ways(&codec, "VarArray", &Value::array([0x01_0203, 0x04_0506]), &VAR_ARRAY_OCTETS);
    let nested = Value::array([Value::array([0x01_0203]), Value::array([0x04_0506, 0x07_0809])]);
    both_ways(&codec, "VarArrays", &nested, &NESTED_OCTETS);
    assert_eq!(codec.octet_boundary("Floats"), Some(8));
    assert_eq!(codec.octet_boundary("VarArray"), Some(4));
    assert_eq!(codec.octet_boundary("VarArrays"), Some(4));
    let error = codec.decode("VarArray", &[0xff, 0xff, 0xff, 0xfe]).unwrap_err();
    assert_eq!(error.reason(), Some(&Reason::Decoder(DecoderError::InvalidCount { count: -2 })));
}

// ---------------------------------------------------------------------------------------------------
// The FOM-driven codec on nested user-defined data types
// ---------------------------------------------------------------------------------------------------

/// A module with nested user-defined data types: a 24-bit simple type, an enumerated type on a 16-bit
/// little-endian representation, a reference whose representation is a fixed record, a variant record
/// over them, a variable array of it and a record around the array.
#[cfg(feature = "fom")]
fn nested_fdd() -> microrti_fom::Fdd {
    let objects = "<objects><objectClass><name>HLAobjectRoot</name><objectClass><name>Thing</name>\
         <sharing>PublishSubscribe</sharing><attribute><name>Where</name><dataType>Point</dataType>\
         <updateType>Static</updateType><updateCondition>NA</updateCondition><ownership>NoTransfer</ownership>\
         <sharing>PublishSubscribe</sharing><transportation>HLAreliable</transportation><order>Receive</order>\
         </attribute></objectClass></objectClass></objects>";
    let tables = Tables::default()
        .basic("U24", 24, "Integer in the range [0, 2^24 - 1]", "Big")
        .simple("Count24", "U24")
        .reference("PointRef", "Point", "HLAobjectRoot.Thing", "Where")
        .enumerated("Mode", "HLAinteger16LE", &[("Off", &[0]), ("On", &[1]), ("Idle", &[2])])
        .array("Readings", "Reading", "Dynamic", "HLAvariableArray")
        .record("Point", &[("X", "HLAfloat32BE"), ("Y", "HLAfloat32BE")])
        .record("Frame", &[("Tag", "HLAoctet"), ("Readings", "Readings"), ("Stamp", "HLAinteger64BE")])
        .variant(
            "Reading",
            "HLAvariantRecord",
            "Mode",
            &[("On", "Count", "Count24"), ("Idle", "Where", "PointRef")],
        );
    fom_support::fdd_with(&format!("{objects}{}", tables.xml()))
}

/// Every padding of a nested value, computed by hand from 4.14.10.1, 4.14.10.2 and 4.14.10.5.
#[cfg(feature = "fom")]
#[test]
fn nested_user_defined_types_in_the_fom_codec() {
    let codec = microrti_encoding::fom::FomCodec::new(&nested_fdd()).unwrap();
    for (name, boundary) in [
        ("Count24", 4),
        ("Mode", 2),
        ("Point", 4),
        ("PointRef", 4),
        ("Reading", 4),
        ("Readings", 4),
        ("Frame", 8),
    ] {
        assert_eq!(codec.octet_boundary(name), Some(boundary), "{name}");
        assert_eq!(codec.raw_reason(name), None, "{name}");
    }
    let point = Value::record([("X", Value::from(1.0)), ("Y", Value::from(-2.5))]);
    let readings = Value::array([
        Value::variant_named(Enumerator::new("On", 1), "Count", 0x01_0203),
        Value::variant(Enumerator::new("Off", 0), None),
        Value::variant_named(Enumerator::new("Idle", 2), "Where", point),
    ]);
    let frame =
        Value::record([("Tag", Value::Octet(0xaa)), ("Readings", readings), ("Stamp", Value::from(5))]);
    let expected = [
        0xaa, 0, 0, 0, // Tag, padding to the boundary 4 of Readings
        0, 0, 0, 3, // count
        1, 0, 0, 0, // On (16-bit little endian), padding to the largest alternative boundary, 4
        1, 2, 3, 0, // Count24 in three octets, padding to the next element
        0, 0, 0, 0, // Off: the discriminant alone, padding to the next element
        2, 0, 0, 0, // Idle, padding
        0x3f, 0x80, 0, 0, 0xc0, 0x20, 0, 0, // PointRef: the Point record
        0, 0, 0, 0, 0, 0, 0, 5, // Stamp, already at a multiple of 8
    ];
    both_ways(&codec, "Frame", &frame, &expected);
}

/// The octet boundary of a data type, computed from its definition by the rules of 4.14.10, 4.14.10.3 and
/// 4.14.10.5, independently of the codec.
#[cfg(feature = "fom")]
fn boundary_by_the_rules(fdd: &microrti_fom::Fdd, name: &str) -> Option<usize> {
    use microrti_fom::DataType;
    let of = |name: Option<&str>| name.and_then(|name| boundary_by_the_rules(fdd, name));
    match fdd.data_type(name)? {
        DataType::Basic(basic) => {
            let bits = usize::try_from(basic.size?).ok()?;
            let mut boundary = 1;
            while 8 * boundary < bits {
                boundary *= 2;
            }
            Some(boundary)
        }
        DataType::Simple(simple) => of(simple.representation.as_deref()),
        DataType::Reference(reference) => of(Some(&reference.representation)),
        DataType::Enumerated(enumerated) => of(enumerated.representation.as_deref()),
        DataType::Array(array) => {
            let element = of(array.data_type.as_deref())?;
            match array.encoding.as_deref()? {
                "HLAfixedArray" => Some(element),
                "HLAvariableArray" => Some(element.max(4)),
                _ => None,
            }
        }
        DataType::FixedRecord(record) => record
            .fields
            .iter()
            .try_fold(1, |boundary, field| Some(boundary.max(of(field.data_type.as_deref())?))),
        DataType::VariantRecord(variant) => {
            let discriminant = of(variant.data_type.as_deref())?;
            match variant.encoding.as_deref()? {
                "HLAextendableVariantRecord" => Some(discriminant.max(4).max(8)),
                "HLAvariantRecord" => variant
                    .alternatives
                    .iter()
                    .filter(|alternative| alternative.data_type.as_deref().is_some_and(|name| name != "NA"))
                    .try_fold(discriminant, |boundary, alternative| {
                        Some(boundary.max(of(alternative.data_type.as_deref())?))
                    }),
                _ => None,
            }
        }
    }
}

/// The codec gives every data type of the MIM, of the Restaurant FOM and of the nested module the
/// octet boundary that the rules give.
#[cfg(feature = "fom")]
#[test]
fn octet_boundaries_of_every_data_type_follow_4_14_10() {
    use microrti_encoding::fom::FomCodec;
    use microrti_fom::{Fdd, parse_module};

    let restaurant = {
        let path = format!("{}/../../fom/RestaurantFOMmodule-2025.xml", env!("CARGO_MANIFEST_DIR"));
        let content = std::fs::read(&path).unwrap();
        let module = parse_module("RestaurantFOMmodule-2025.xml", &content).unwrap();
        Fdd::create(None, &[module]).unwrap().0
    };
    let mut checked = 0;
    for fdd in [Fdd::with_standard_mim(), restaurant, nested_fdd()] {
        let codec = FomCodec::new(&fdd).unwrap();
        for data_type in fdd.data_types() {
            let name = data_type.name();
            if codec.raw_reason(name).is_some() {
                continue;
            }
            assert_eq!(codec.octet_boundary(name), boundary_by_the_rules(&fdd, name), "{name}");
            checked += 1;
        }
    }
    assert!(checked > 150, "only {checked} data types checked");
}

// ---------------------------------------------------------------------------------------------------
// Hostile input on the rules this file changed
// ---------------------------------------------------------------------------------------------------

/// Decodes `bytes` as `T`; when that works, the canonical encoding decodes and encodes again to itself.
fn round_trip_if_accepted<T: Decode + std::fmt::Debug>(bytes: &[u8]) -> usize {
    let Ok((value, used)) = decode_prefix::<T>(bytes) else {
        return 0;
    };
    assert!(used <= bytes.len());
    let canonical = encode_to_vec(&value);
    let again =
        decode_from_slice_strict::<T>(&canonical).unwrap_or_else(|error| panic!("{value:?}: {error}"));
    assert_eq!(encode_to_vec(&again), canonical);
    1
}

fn typed_and_dynamic(bytes: &[u8], extendable: &mut HLAextendableVariantRecord) -> usize {
    let mut accepted = round_trip_if_accepted::<Example2>(bytes)
        + round_trip_if_accepted::<Example3>(bytes)
        + round_trip_if_accepted::<Wide>(bytes)
        + round_trip_if_accepted::<Narrow>(bytes)
        + round_trip_if_accepted::<Framed3>(bytes)
        + round_trip_if_accepted::<Vec<U24>>(bytes)
        + round_trip_if_accepted::<Vec<Vec<U24>>>(bytes)
        + round_trip_if_accepted::<[IntegerThenOctet; 2]>(bytes)
        + round_trip_if_accepted::<OctetBooleanFloat>(bytes)
        + round_trip_if_accepted::<Vec<Wide>>(bytes);
    if extendable.decode_slice(bytes).is_ok()
        && let Ok(canonical) = extendable.to_bytes()
    {
        let mut again = extendable.clone();
        again.decode_slice_strict(&canonical).expect("canonical encoding decodes");
        assert_eq!(again.to_bytes().as_ref(), Ok(&canonical));
        accepted += 1;
    }
    accepted
}

/// Noise and mutated encodings never make the typed layer or the dynamic containers panic, and
/// what they accept has a stable canonical encoding.
#[test]
fn hostile_octets_on_the_changed_rules() {
    let mut random = common::XorShift(0x4_1410_0003);
    let mut extendable = HLAextendableVariantRecord::new(HLAinteger64BE(0));
    extendable.set_variant(HLAinteger64BE(1), HLAinteger16BE(0)).unwrap();
    extendable.set_empty_variant(HLAinteger64BE(3)).unwrap();
    let mut accepted = 0;
    for _ in 0..3000 {
        let len = random.below(64);
        let mut bytes = random.bytes(len);
        // Small discriminants and lengths now and then, so that decoding gets further.
        for at in [0, 7, 11] {
            if bytes.len() > at && random.below(2) == 0 {
                bytes[at] = random.below(4) as u8;
            }
        }
        accepted += typed_and_dynamic(&bytes, &mut extendable);
    }
    let seeds = [
        encode_to_vec(&vec![Wide::Short(HLAinteger16BE(7)), Wide::Nothing, Wide::Token([])]),
        encode_to_vec(&Framed3 {
            head: HLAoctet(1),
            body: Example3::Float(HLAfloat32LE(1.0)),
            tail: HLAoctet(2),
        }),
        encode_to_vec(&vec![vec![U24(1)], vec![U24(2), U24(3)]]),
        encode_to_vec(&Example2::Pair(TwoOctets::default())),
    ];
    for seed in &seeds {
        for position in 0..seed.len() {
            for replacement in [0x00, 0x01, 0x03, 0x7f, 0x80, 0xff, random.next() as u8] {
                let mut bytes = seed.clone();
                bytes[position] = replacement;
                accepted += typed_and_dynamic(&bytes, &mut extendable);
            }
        }
        for len in 0..seed.len() {
            typed_and_dynamic(&seed[..len], &mut extendable);
        }
    }
    assert!(accepted > 500, "only {accepted} inputs accepted");
}

/// The same through the FOM codec, on data types with odd sizes, padding bits, variant records
/// with enumerators without alternative and extendable records with a 64-bit discriminant; and hostile
/// definitions (huge sizes) stay raw instead of costing memory.
#[cfg(feature = "fom")]
#[test]
fn hostile_octets_on_the_changed_rules_in_the_fom_codec() {
    use microrti_encoding::fom::{CodecError, FomCodec};

    let tables = Tables::default()
        .basic("U12", 12, "Integer in the range [0, 2^12 - 1]", "Big")
        .basic("S24", 24, "Two's complement integer", "Little")
        .basic("Opaque100", 100, "100-bit value", "Big")
        .basic("Huge", u32::MAX, "Very large", "Big")
        .enumerated("Choice", "HLAoctet", &[("A", &[1]), ("B", &[2]), ("C", &[3])])
        .enumerated("WideChoice", "HLAinteger64BE", &[("S", &[1]), ("N", &[3])])
        .array("U12s", "U12", "Dynamic", "HLAvariableArray")
        .array("Opaques", "Opaque100", "2", "HLAfixedArray")
        .record("Mixed", &[("A", "HLAoctet"), ("B", "S24"), ("C", "U12s"), ("D", "Opaques")])
        .variant("Plain", "HLAvariantRecord", "Choice", &[("A", "X", "S24"), ("B", "Y", "Opaque100")])
        .variant("Open", "HLAextendableVariantRecord", "WideChoice", &[("S", "Short", "U12")])
        .array("Opens", "Open", "Dynamic", "HLAvariableArray")
        .array("Plains", "Plain", "Dynamic", "HLAvariableArray");
    let fdd = fom_support::fdd_with(&tables.xml());
    let codec = FomCodec::new(&fdd).unwrap();
    assert!(codec.raw_reason("Huge").is_some());
    let names = ["U12", "S24", "Opaque100", "U12s", "Opaques", "Mixed", "Plain", "Open", "Opens", "Plains"];
    let mut random = common::XorShift(0x0001_5162_4141);
    let mut accepted = 0;
    let mut attempt = |bytes: &[u8]| {
        for name in names {
            match codec.decode_prefix(name, bytes) {
                Ok((value, used)) => {
                    assert!(used <= bytes.len());
                    accepted += 1;
                    let canonical =
                        codec.encode(name, &value).unwrap_or_else(|error| panic!("{name}: {error}"));
                    let again =
                        codec.decode(name, &canonical).unwrap_or_else(|error| panic!("{name}: {error}"));
                    assert_eq!(codec.encode(name, &again), Ok(canonical), "{name}");
                }
                Err(error) => {
                    assert!(matches!(error, CodecError::Decode(_)), "{error}");
                    assert!(error.offset().is_some_and(|offset| offset <= bytes.len()), "{error}");
                }
            }
        }
    };
    for _ in 0..2000 {
        let len = random.below(64);
        let mut bytes = random.bytes(len);
        for at in [0, 3, 7, 11] {
            if bytes.len() > at && random.below(2) == 0 {
                bytes[at] = random.below(4) as u8;
            }
        }
        attempt(&bytes);
    }
    let seeds = [
        vec![0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0x0f, 0xff],
        vec![0, 0, 0, 2, 2, 0, 0, 0, 0x0f, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 3],
        vec![1, 0xfe, 0xff, 0xff, 0, 0, 0, 1, 0x0a, 0xbc],
    ];
    for seed in &seeds {
        for position in 0..seed.len() {
            for replacement in [0x00, 0x01, 0x10, 0x80, 0xff, random.next() as u8] {
                let mut bytes = seed.clone();
                bytes[position] = replacement;
                attempt(&bytes);
            }
        }
    }
    assert!(accepted > 500, "only {accepted} inputs accepted");
}