canboat 9.1.0

NMEA 2000 decoding, encoding and live-bus access: the CANboat PGN database as a library, plus the canboat CLI (convert / interface / server / tui).
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
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
// (C) 2009-2026, Kees Verruijt, Harlingen, The Netherlands.

//! Encode a PGN from field values into a wire [`RawFrame`] — the
//! inverse of [`crate::engine::decode`].
//!
//! The entry point is [`PgnDatabase::encode`] /
//! [`PgnDatabase::encode_by_pgn`] (by id / by number), or
//! [`PgnDatabase::encode_for`] with a generated `pgn::…` constant, which
//! hand back a [`PgnBuilder`] for a specific schema PGN variant. Set
//! field values by a compile-checked `field::…` constant
//! ([`push`](PgnBuilder::push) — the O(1) default) or by schema name
//! ([`push_by_name`](PgnBuilder::push_by_name)), mirroring the decode
//! side's [`DecodedPgn::field`] / [`DecodedPgn::field_by_name`];
//! then [`build`](PgnBuilder::build) packs them at their schema bit
//! offsets — LSB-first, exactly the layout [`crate::engine::bits::extract_bits`]
//! reads back — and returns a [`RawFrame`]. Because the result is a
//! `RawFrame`, any [`crate::engine::format`] writer (PLAIN, YDWG02, Actisense,
//! `.ebl`) turns it into wire text/bytes.
//!
//! Fields the caller doesn't set are filled automatically: a field with
//! a `match_value` (the raw value that selects this PGN variant) gets
//! that value, so proprietary/variant PGNs come out valid without the
//! caller restating their manufacturer/industry/selector fields; a
//! `Spare` field gets zero; everything else gets its "not available"
//! sentinel (the schema `unknown_value`, else all-ones).
//!
//! Scope: every self-contained field type encodes — the numeric,
//! enum/lookup, PGN/MMSI, `FLOAT`, `ISO_NAME`, `BINARY` and all four
//! string families (`STRING_FIX`/`LZ`/`LAU`). The key/value family
//! ([`DynamicFieldKey`](FieldType::DynamicFieldKey) /
//! [`DynamicFieldValue`](FieldType::DynamicFieldValue), e.g. PGN 130845
//! `simnetKeyValue`) encodes when set explicitly: the KEY is a
//! fixed-width scalar (set it as an `Int`), and the VALUE takes its bytes
//! verbatim (set it as `Bytes` — the caller owns matching the width the
//! resolved key expects). Left unset, the VALUE and the PGN 126208
//! group-function types (`VARIABLE`, `DYNAMIC_FIELD_LENGTH`) can't be
//! defaulted in isolation and return [`EncodeError::NotFixedLength`].

use std::error::Error;
use std::fmt;

use crate::engine::decode::field_present;
use crate::engine::types::{FieldInfo, FieldRef, FieldType, PgnInfo};

use crate::engine::db::PgnDatabase;
use crate::engine::frame::RawFrame;

/// A value to place into a PGN field when encoding. Owned and
/// caller-constructible (unlike the decode [`crate::engine::FieldValue`], which
/// borrows `&'static` schema references).
#[derive(Debug, Clone, PartialEq)]
pub enum EncodeValue {
    /// A physical value in the field's unit (e.g. `1.23` rad/s).
    /// Inverse of the decoder's `raw * resolution + offset + unit_offset`.
    Number(f64),
    /// An integer value. Means exactly what the same [`Number`] would: a
    /// value in the field's unit, so `1000` and `1000.0` W encode alike.
    /// On a field whose value is a code (a `LOOKUP` / `BITLOOKUP` code,
    /// a PGN, MMSI or ISO NAME) it is that code. Kept apart from `Number`
    /// so that a field without scaling takes it exactly, beyond `f64`'s
    /// 53 bits.
    ///
    /// [`Number`]: EncodeValue::Number
    Int(i64),
    /// The field's wire bits, written verbatim: no scaling and no range
    /// check, so it can write a sentinel ("not available", "error") on
    /// purpose. The only way to ask for raw bits; build it with
    /// [`Raw`].
    Raw(u64),
    /// A `LOOKUP` / `BITLOOKUP` selected by its label (e.g. `"Apparent"`).
    Lookup(String),
    /// Text for a `STRING_FIX` / `STRING_LZ` / `STRING_LAU` field.
    Text(String),
    /// Raw bytes for a `BINARY` field.
    Bytes(Vec<u8>),
    /// A PGN number for a `PGN`-type field (packed as its bit-width,
    /// LSB-first → little-endian bytes).
    Pgn(u32),
    /// Leave the field at its "not available" sentinel.
    NotAvailable,
}

/// The wire bits of a field, for [`PgnBuilder::push`]: `push(f, Raw(0xffff))`
/// writes them verbatim, where `push(f, 0xffff)` is a value in the field's
/// unit. See [`EncodeValue::Raw`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Raw(pub u64);

impl From<Raw> for EncodeValue {
    fn from(v: Raw) -> Self {
        EncodeValue::Raw(v.0)
    }
}

impl From<f64> for EncodeValue {
    fn from(v: f64) -> Self {
        EncodeValue::Number(v)
    }
}
impl From<i64> for EncodeValue {
    fn from(v: i64) -> Self {
        EncodeValue::Int(v)
    }
}
impl From<i32> for EncodeValue {
    fn from(v: i32) -> Self {
        EncodeValue::Int(v as i64)
    }
}
impl From<u32> for EncodeValue {
    fn from(v: u32) -> Self {
        EncodeValue::Int(v as i64)
    }
}
impl From<&str> for EncodeValue {
    fn from(v: &str) -> Self {
        EncodeValue::Text(v.to_string())
    }
}
impl From<String> for EncodeValue {
    fn from(v: String) -> Self {
        EncodeValue::Text(v)
    }
}
impl From<Vec<u8>> for EncodeValue {
    fn from(v: Vec<u8>) -> Self {
        EncodeValue::Bytes(v)
    }
}
impl From<&[u8]> for EncodeValue {
    fn from(v: &[u8]) -> Self {
        EncodeValue::Bytes(v.to_vec())
    }
}

/// Why a message could not be encoded. Non-exhaustive: new ways to fail
/// can be added without a breaking release.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum EncodeError {
    /// No PGN with this schema id (e.g. `"isoRequest"`).
    NoSuchPgnId(String),
    /// No PGN with this number in the schema.
    NoSuchPgn(u32),
    /// This PGN number has several schema variants; use
    /// [`PgnDatabase::encode`] with the specific id.
    AmbiguousPgn { pgn: u32, variants: usize },
    /// No field with this name/id in the PGN.
    NoSuchField { pgn_id: &'static str, field: String },
    /// A `LOOKUP` field was given a label that isn't in its table.
    UnknownLookupLabel { field: &'static str, label: String },
    /// A value doesn't fit the field's bit width / range. `range` is the
    /// field's valid range in the schema's unit, when the value is a
    /// number outside it.
    ValueOutOfRange {
        field: &'static str,
        value: f64,
        range: Option<(f64, f64)>,
    },
    /// A group-function *dynamic* field (`VARIABLE` /
    /// `DYNAMIC_FIELD_KEY`/`LENGTH`/`VALUE`) was left unset — its width is
    /// determined by sibling fields, so it can't be defaulted in isolation.
    NotFixedLength(&'static str),
    /// The field type can't accept the [`EncodeValue`] variant given.
    TypeMismatch {
        field: &'static str,
        expected: &'static str,
    },
    /// The packed byte length didn't match the PGN's declared length —
    /// an internal consistency failure (repeating/variable PGN, or a
    /// schema/encoder mismatch).
    LengthMismatch { pgn: u32, expected: u32, got: usize },
    /// A group-function `VARIABLE` value could not be resolved against
    /// the referenced PGN's field (missing/unknown target PGN or
    /// FIELD_INDEX).
    VariableUnresolved {
        field: &'static str,
        reason: &'static str,
    },
    /// [`PgnBuilder::add_set_instance`] / [`PgnBuilder::push_in_set`]
    /// was called for a repeating set this PGN does not declare.
    NoRepeatingSet { pgn_id: &'static str, set: usize },
    /// [`PgnBuilder::push_in_set`] addressed an instance index that was
    /// never created with [`PgnBuilder::add_set_instance`].
    NoSuchInstance {
        pgn_id: &'static str,
        set: usize,
        instance: usize,
    },
    /// The Manufacturer Code / Industry Code header of a 126208 Read or
    /// Write Fields (or their replies) is in the message only when the
    /// commanded PGN is proprietary. `proprietary` says which way it went
    /// wrong: `true` when a proprietary `target_pgn` left `field` unset,
    /// `false` when `field` was set for a PGN that is not proprietary
    /// (`None` when no PGN was set at all).
    ProprietaryHeader {
        field: &'static str,
        target_pgn: Option<u32>,
        proprietary: bool,
    },
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EncodeError::NoSuchPgnId(id) => write!(f, "no PGN with id '{id}'"),
            EncodeError::NoSuchPgn(p) => write!(f, "no PGN {p} in the schema"),
            EncodeError::AmbiguousPgn { pgn, variants } => {
                write!(f, "PGN {pgn} has {variants} variants; select one by id")
            }
            EncodeError::NoSuchField { pgn_id, field } => {
                write!(f, "PGN '{pgn_id}' has no field '{field}'")
            }
            EncodeError::UnknownLookupLabel { field, label } => {
                write!(f, "field '{field}': '{label}' is not a valid value")
            }
            EncodeError::ValueOutOfRange {
                field,
                value,
                range: Some((min, max)),
            } => {
                write!(
                    f,
                    "field '{field}': value {value} is outside its range {min} to {max}"
                )
            }
            EncodeError::ValueOutOfRange {
                field,
                value,
                range: None,
            } => {
                write!(f, "field '{field}': value {value} out of range")
            }
            EncodeError::NotFixedLength(field) => {
                write!(
                    f,
                    "field '{field}': dynamic group-function field must be set explicitly"
                )
            }
            EncodeError::VariableUnresolved { field, reason } => {
                write!(f, "field '{field}': {reason}")
            }
            EncodeError::NoRepeatingSet { pgn_id, set } => {
                write!(f, "PGN '{pgn_id}' has no repeating field set {set}")
            }
            EncodeError::NoSuchInstance {
                pgn_id,
                set,
                instance,
            } => {
                write!(
                    f,
                    "PGN '{pgn_id}' set {set}: instance {instance} was never added"
                )
            }
            EncodeError::TypeMismatch { field, expected } => {
                write!(f, "field '{field}': expected {expected}")
            }
            EncodeError::ProprietaryHeader {
                field,
                target_pgn: Some(pgn),
                proprietary: true,
            } => {
                write!(f, "field '{field}' must be set: PGN {pgn} is proprietary")
            }
            EncodeError::ProprietaryHeader {
                field,
                target_pgn: Some(pgn),
                proprietary: false,
            } => {
                write!(
                    f,
                    "field '{field}' is only sent for a proprietary PGN, and {pgn} is not"
                )
            }
            EncodeError::ProprietaryHeader {
                field,
                target_pgn: None,
                ..
            } => {
                write!(
                    f,
                    "field '{field}' is only sent for a proprietary PGN, and no PGN is set"
                )
            }
            EncodeError::LengthMismatch { pgn, expected, got } => {
                write!(f, "PGN {pgn}: packed {got} bytes, schema says {expected}")
            }
        }
    }
}

impl Error for EncodeError {}

/// Fluent builder for one PGN message. Created via
/// [`PgnDatabase::encode`] / [`PgnDatabase::encode_by_pgn`].
pub struct PgnBuilder {
    db: &'static PgnDatabase,
    pgn: &'static PgnInfo,
    prio: u8,
    src: u8,
    dst: u8,
    timestamp: Option<String>,
    /// Staged values per field, indexed by `order - 1`. `None` → fill
    /// with the field default at build time. For fields inside a
    /// repeating set these slots are ignored; instances live in `sets`.
    staged: Vec<Option<Staged>>,
    /// Staged repeating-set instances: `sets[0]` for set 1, `sets[1]`
    /// for set 2. Each instance stages the set's fields by position
    /// within the set (`order - start_field`). Zero instances → the
    /// payload simply ends before the set, mirroring decode.
    sets: [Vec<Vec<Option<Staged>>>; 2],
}

/// A staged field value: either a scalar bit pattern (numbers, lookups,
/// PGN references) or already-packed bytes (a fixed-length string).
#[derive(Clone)]
enum Staged {
    /// Raw bits, LSB-first, of the field's declared width.
    Scalar(u64),
    /// Byte-aligned payload of exactly `bit_length / 8` bytes.
    Bytes(Vec<u8>),
    /// A group-function `VARIABLE` value, staged as-given: its width,
    /// scaling and type come from the *referenced* PGN's field, which
    /// is only known at build time (the record's PGN field plus the
    /// instance's FIELD_INDEX select it). Resolved by
    /// [`PgnBuilder::build`] exactly as the decoder resolves it.
    Deferred(EncodeValue),
}

impl PgnBuilder {
    /// Construct for a resolved PGN variant. Crate-internal; callers go
    /// through [`PgnDatabase::encode`].
    pub(crate) fn for_pgn(db: &'static PgnDatabase, pgn: &'static PgnInfo) -> Self {
        Self {
            db,
            pgn,
            // A Quick message has no priority (an 11-bit identifier is
            // only its type); 6 is the ISO 11783 default for the others.
            prio: if db.protocol().standard_frames() {
                0
            } else {
                pgn.priority.unwrap_or(6)
            },
            src: 0,
            dst: 255,
            timestamp: None,
            staged: vec![None; pgn.fields.len()],
            sets: [Vec::new(), Vec::new()],
        }
    }

    /// Override the CAN priority (default: the schema priority, else 6).
    pub fn priority(mut self, prio: u8) -> Self {
        self.prio = prio;
        self
    }
    /// Set the source address (default 0).
    pub fn source(mut self, src: u8) -> Self {
        self.src = src;
        self
    }
    /// Set the destination address (default 255 = broadcast).
    pub fn destination(mut self, dst: u8) -> Self {
        self.dst = dst;
        self
    }
    /// Stamp a timestamp onto the produced frame (default: none — the
    /// caller/writer decides).
    pub fn timestamp(mut self, ts: impl Into<String>) -> Self {
        self.timestamp = Some(ts.into());
        self
    }

    /// Set a field by its generated [`FieldRef`] constant
    /// (`crate::engine::field::wind_data::WIND_ANGLE`) — the compile-checked,
    /// `O(1)` path, and the recommended default. The exact mirror of the
    /// decode side's [`DecodedPgn::field`](crate::engine::DecodedPgn::field): index
    /// by the field's schema `order` (one array load), with a debug-only
    /// assert that the constant belongs to this builder's PGN — a `&str`
    /// compare, free in release builds, no scan and no hashing.
    ///
    /// The value scales in the builder's unit system: the constant points at
    /// the SI schema, but a field's `order` is identical across unit schemas,
    /// so the builder's own [`FieldInfo`] (in its units) does the staging.
    pub fn push(
        &mut self,
        field: FieldRef,
        value: impl Into<EncodeValue>,
    ) -> Result<&mut Self, EncodeError> {
        debug_assert_eq!(
            field.pgn.id, self.pgn.id,
            "FieldRef/PGN mismatch: a `{}` field ref was used on a `{}` builder",
            field.pgn.id, self.pgn.id,
        );
        let idx = (field.field.order as usize)
            .checked_sub(1)
            .filter(|&i| i < self.pgn.fields.len())
            .ok_or(EncodeError::NoSuchField {
                pgn_id: self.pgn.id,
                field: field.field.id.to_string(),
            })?;
        let staged = self.stage_value(&self.pgn.fields[idx], value.into())?;
        self.staged[idx] = Some(staged);
        Ok(self)
    }

    /// Set a field by schema **name** (`"Wind Speed"`) — an `O(n)` scan, for
    /// callers without a [`FieldRef`] constant (runtime-chosen or
    /// config-driven fields). The mirror of
    /// [`DecodedPgn::field_by_name`](crate::engine::DecodedPgn::field_by_name).
    /// Prefer [`push`](Self::push) with a generated constant wherever the
    /// field is known at compile time: it is O(1) and a typo fails the build
    /// instead of returning [`EncodeError::NoSuchField`] at runtime.
    pub fn push_by_name(
        &mut self,
        field: &str,
        value: impl Into<EncodeValue>,
    ) -> Result<&mut Self, EncodeError> {
        let idx = self.find_by_name(field)?;
        let staged = self.stage_value(&self.pgn.fields[idx], value.into())?;
        self.staged[idx] = Some(staged);
        Ok(self)
    }

    /// Set a field from a textual value, coercing per the field's type
    /// (numbers, `0x`-hex, lookup labels). For CLI `FIELD=VALUE` args, where
    /// `FIELD` may be the schema name (`"Wind Speed"`) or id (`"windSpeed"`).
    pub fn push_arg(&mut self, field: &str, value: &str) -> Result<&mut Self, EncodeError> {
        let idx = self.find_by_name_or_id(field)?;
        let f = &self.pgn.fields[idx];
        let ev = coerce_arg(f, value)?;
        let staged = self.stage_value(f, ev)?;
        self.staged[idx] = Some(staged);
        Ok(self)
    }

    /// Resolve repeating set `set` (1 or 2) to `(start index, size,
    /// count-field index)`, all zero-based, or `None` if this PGN does
    /// not declare that set.
    fn set_layout(&self, set: usize) -> Option<(usize, usize, Option<usize>)> {
        let (start, size, count) = match set {
            1 => (
                self.pgn.repeating_field_set1_start_field,
                self.pgn.repeating_field_set1_size,
                self.pgn.repeating_field_set1_count_field,
            ),
            2 => (
                self.pgn.repeating_field_set2_start_field,
                self.pgn.repeating_field_set2_size,
                self.pgn.repeating_field_set2_count_field,
            ),
            _ => (None, None, None),
        };
        Some((
            start? as usize - 1,
            size? as usize,
            count.map(|c| c as usize - 1),
        ))
    }

    /// Append a new instance of repeating set `set` (1 or 2) and return
    /// its index for [`push_in_set`](Self::push_in_set). Fields left
    /// unset in an instance are filled with their "not available"
    /// defaults at build time, exactly like top-level fields. The set's
    /// count field (when the schema declares one) is set automatically
    /// from the number of instances unless staged explicitly.
    pub fn add_set_instance(&mut self, set: usize) -> Result<usize, EncodeError> {
        let (_, size, _) = self.set_layout(set).ok_or(EncodeError::NoRepeatingSet {
            pgn_id: self.pgn.id,
            set,
        })?;
        let instances = &mut self.sets[set - 1];
        instances.push(vec![None; size]);
        Ok(instances.len() - 1)
    }

    /// Set a field of repeating-set instance `instance` by schema name
    /// (`"Parameter"`) or id (`"parameter"`). The instance must have
    /// been created with [`add_set_instance`](Self::add_set_instance).
    pub fn push_in_set(
        &mut self,
        set: usize,
        instance: usize,
        field: &str,
        value: impl Into<EncodeValue>,
    ) -> Result<&mut Self, EncodeError> {
        let (start, size, _) = self.set_layout(set).ok_or(EncodeError::NoRepeatingSet {
            pgn_id: self.pgn.id,
            set,
        })?;
        let rel = self.pgn.fields[start..start + size]
            .iter()
            .position(|f| f.name == field || f.id == field)
            .ok_or_else(|| EncodeError::NoSuchField {
                pgn_id: self.pgn.id,
                field: field.to_string(),
            })?;
        let f = &self.pgn.fields[start + rel];
        // A VARIABLE value can't be staged yet — its metadata lives in
        // the referenced PGN's field, selected by the record's PGN
        // field and this instance's FIELD_INDEX. Defer to build().
        let staged = if f.field_type == Some(FieldType::Variable) {
            Staged::Deferred(value.into())
        } else {
            self.stage_value(f, value.into())?
        };
        let inst = self.sets[set - 1]
            .get_mut(instance)
            .ok_or(EncodeError::NoSuchInstance {
                pgn_id: self.pgn.id,
                set,
                instance,
            })?;
        inst[rel] = Some(staged);
        Ok(self)
    }

    /// Build the wire frame: pack every field (staged value or default)
    /// LSB-first at its schema offset, verify the length, and return the
    /// [`RawFrame`]. Repeating sets are emitted at their schema position,
    /// one group per staged instance (zero instances → the payload ends
    /// there, mirroring decode); a declared count field left unset is
    /// filled with the instance count.
    pub fn build(&self) -> Result<RawFrame, EncodeError> {
        let mut buf: Vec<u8> = Vec::new();
        let mut next_bit = 0usize;
        let set1 = self.set_layout(1);
        let set2 = self.set_layout(2);
        let mut idx = 0usize;
        while idx < self.pgn.fields.len() {
            // A repeating set starts at this field? Emit its staged
            // instances and skip past the group's schema fields.
            let mut in_set = false;
            for (layout, instances) in [(&set1, &self.sets[0]), (&set2, &self.sets[1])] {
                if let Some((start, size, _)) = *layout
                    && idx == start
                {
                    for inst in instances {
                        for (j, f) in self.pgn.fields[start..start + size].iter().enumerate() {
                            match &inst[j] {
                                Some(Staged::Deferred(v)) => self.emit_variable(
                                    &mut buf,
                                    &mut next_bit,
                                    f,
                                    inst,
                                    start,
                                    size,
                                    v,
                                )?,
                                None => {
                                    let fields = &self.pgn.fields[start..start + size];
                                    let derived = continuing_staged(fields, inst, j);
                                    emit_field(
                                        &mut buf,
                                        &mut next_bit,
                                        self.pgn.pgn,
                                        f,
                                        derived.as_ref(),
                                    )?
                                }
                                other => emit_field(
                                    &mut buf,
                                    &mut next_bit,
                                    self.pgn.pgn,
                                    f,
                                    other.as_ref(),
                                )?,
                            }
                        }
                    }
                    idx += size;
                    in_set = true;
                    break;
                }
            }
            if in_set {
                continue;
            }
            let f = &self.pgn.fields[idx];
            // The Manufacturer / Industry header of a 126208 Read or Write
            // Fields is in the message exactly when the commanded PGN is
            // proprietary, as decode reads it: required then (bar its
            // Reserved bits), and refused otherwise, as it would shift
            // every later field.
            if f.condition.is_some() {
                let target_pgn = self.staged_target_pgn();
                let staged = self.staged[idx].is_some();
                if !field_present(f.condition, target_pgn) {
                    if staged {
                        return Err(EncodeError::ProprietaryHeader {
                            field: f.name,
                            target_pgn,
                            proprietary: false,
                        });
                    }
                    idx += 1;
                    continue;
                }
                if !staged && f.field_type != Some(FieldType::Reserved) {
                    return Err(EncodeError::ProprietaryHeader {
                        field: f.name,
                        target_pgn,
                        proprietary: true,
                    });
                }
            }
            // A declared count field left unset takes the number of
            // staged instances for its set (0 when none were added — a
            // zero-iteration message, not "unavailable").
            let auto_count = [(&set1, &self.sets[0]), (&set2, &self.sets[1])]
                .into_iter()
                .find_map(|(layout, instances)| match *layout {
                    Some((_, _, Some(count_idx)))
                        if count_idx == idx && self.staged[idx].is_none() =>
                    {
                        Some(Staged::Scalar(instances.len() as u64))
                    }
                    _ => None,
                });
            let derived = match self.staged[idx] {
                None => continuing_staged(self.pgn.fields, &self.staged, idx),
                Some(_) => None,
            };
            emit_field(
                &mut buf,
                &mut next_bit,
                self.pgn.pgn,
                f,
                auto_count
                    .as_ref()
                    .or(self.staged[idx].as_ref())
                    .or(derived.as_ref()),
            )?;
            idx += 1;
        }
        // Flush a trailing partial byte (LSB-first packing already grew
        // the buffer as it went, so this is only defensive).
        if !next_bit.is_multiple_of(8) {
            // pad the final byte with 1s (canboat reserved/pad convention)
            let pad = 8 - (next_bit % 8);
            write_bits(&mut buf, &mut next_bit, pad, u64::MAX);
        }
        if let Some(expected) = self.pgn.length
            && buf.len() != expected as usize
        {
            return Err(EncodeError::LengthMismatch {
                pgn: self.pgn.pgn,
                expected,
                got: buf.len(),
            });
        }
        Ok(RawFrame {
            timestamp: self.timestamp.clone(),
            prio: self.prio,
            pgn: self.pgn.pgn,
            src: self.src,
            dst: self.dst,
            data: buf.into_iter().collect(),
        })
    }

    /// The resolved PGN this builder targets (for CLI help / listing).
    pub fn pgn_info(&self) -> &'static PgnInfo {
        self.pgn
    }

    /// Field index by schema name only (for [`push_by_name`](Self::push_by_name)).
    fn find_by_name(&self, name: &str) -> Result<usize, EncodeError> {
        self.pgn
            .fields
            .iter()
            .position(|f| f.name == name)
            .ok_or_else(|| EncodeError::NoSuchField {
                pgn_id: self.pgn.id,
                field: name.to_string(),
            })
    }

    /// Field index by schema name or id (for CLI [`push_arg`](Self::push_arg)).
    fn find_by_name_or_id(&self, key: &str) -> Result<usize, EncodeError> {
        self.pgn
            .fields
            .iter()
            .position(|f| f.name == key || f.id == key)
            .ok_or_else(|| EncodeError::NoSuchField {
                pgn_id: self.pgn.id,
                field: key.to_string(),
            })
    }

    /// Every staged group-function parameter pair across both repeating
    /// sets: the instance's FIELD_INDEX scalar and its deferred VARIABLE
    /// value. Feeds [`match_target_variant`](Self::match_target_variant).
    fn staged_parameter_pairs(&self) -> Vec<(u32, &EncodeValue)> {
        let mut pairs = Vec::new();
        for set in 1..=2 {
            let Some((start, size, _)) = self.set_layout(set) else {
                continue;
            };
            for inst in &self.sets[set - 1] {
                let mut index = None;
                let mut value = None;
                for (j, tf) in self.pgn.fields[start..start + size].iter().enumerate() {
                    match &inst[j] {
                        Some(Staged::Scalar(n)) if tf.field_type == Some(FieldType::FieldIndex) => {
                            index = Some(*n as u32)
                        }
                        Some(Staged::Deferred(v)) => value = Some(v),
                        _ => {}
                    }
                }
                if let (Some(i), Some(v)) = (index, value) {
                    pairs.push((i, v));
                }
            }
        }
        pairs
    }

    /// The PGN the message's PGN field names (a group function's
    /// commanded PGN), when it is staged.
    fn staged_target_pgn(&self) -> Option<u32> {
        self.pgn
            .fields
            .iter()
            .position(|tf| tf.field_type == Some(FieldType::Pgn))
            .and_then(|i| match self.staged[i] {
                Some(Staged::Scalar(p)) => Some(p as u32),
                _ => None,
            })
    }

    /// Pick the definition of `target_pgn` that the staged parameter
    /// pairs describe — the encode-side mirror of decode's
    /// `match_pgn_by_parameters` (itself a port of the C analyzer's
    /// `getMatchingPgnByParameters`). Like the C, it starts past a
    /// catch-all listed first, so a 126720 request naming Airmar and
    /// proprietary ID 35 uses Airmar's Simulate Mode layout. A candidate
    /// qualifies when every pair that lands on one of its `Match` fields
    /// stages to exactly the match value; the first qualifying variant
    /// wins, and a PGN whose first specific definition has no match
    /// fields is answered by it outright. Returns `None` when nothing
    /// can be narrowed — the caller falls back to the leading
    /// definition, which for 126720 is its catch-all.
    fn match_target_variant(&self, target_pgn: u32) -> Option<&'static PgnInfo> {
        let first = self.db.specific_variants(target_pgn).next()?;
        if !first.fields.iter().any(|fi| fi.match_value.is_some()) {
            return Some(first);
        }
        let pairs = self.staged_parameter_pairs();
        // A proprietary target can only be narrowed by Manufacturer
        // (field 1) followed by Industry Code (field 3); like the C,
        // bail out rather than guess when they don't lead the list.
        if crate::engine::decode::is_pgn_proprietary(target_pgn)
            && (pairs.len() < 2 || pairs[0].0 != 1 || pairs[1].0 != 3)
        {
            return None;
        }
        'variant: for cand in self.db.specific_variants(target_pgn) {
            for &(idx, value) in &pairs {
                if idx == 0 {
                    continue 'variant;
                }
                let Some(field) = cand.fields.get(idx as usize - 1) else {
                    continue 'variant;
                };
                let Some(want) = field.match_value else {
                    continue;
                };
                // A label for a lookup-typed match field arrives as
                // Text; retype it the same way emit_variable does.
                let staged_value = match value {
                    EncodeValue::Text(s) if field.lookup_enumeration.is_some() => {
                        EncodeValue::Lookup(s.clone())
                    }
                    other => other.clone(),
                };
                match self.stage_value(field, staged_value) {
                    Ok(Staged::Scalar(raw)) if raw as i64 == want => {}
                    _ => continue 'variant,
                }
            }
            return Some(cand);
        }
        None
    }

    /// Emit a deferred group-function `VARIABLE` value: resolve the
    /// referenced PGN (the record's staged PGN field) and the target
    /// field (this instance's staged FIELD_INDEX), stage the value with
    /// the target field's metadata — width, resolution, lookup table —
    /// and pack it rounded up to whole bytes, mirroring the decoder's
    /// `fieldPrintVariable` byte alignment.
    #[allow(clippy::too_many_arguments)]
    fn emit_variable(
        &self,
        buf: &mut Vec<u8>,
        next_bit: &mut usize,
        f: &FieldInfo,
        inst: &[Option<Staged>],
        start: usize,
        size: usize,
        v: &EncodeValue,
    ) -> Result<(), EncodeError> {
        let unresolved = |reason| EncodeError::VariableUnresolved {
            field: f.name,
            reason,
        };
        let target_pgn = self
            .staged_target_pgn()
            .ok_or(unresolved("no staged PGN field names the referenced PGN"))?;
        // Resolve the target the way decode does: first let the staged
        // parameter pairs pick the variant (a command that sets
        // Manufacturer=Furuno must use the Furuno variant's widths, not
        // whichever definition happens to be listed first), then fall
        // back to the leading definition, then to the range catch-all.
        let target_info = self
            .match_target_variant(target_pgn)
            .or_else(|| self.db.first_pgn(target_pgn))
            .or_else(|| self.db.fallback_pgn(target_pgn))
            .ok_or(unresolved("referenced PGN is not in the schema"))?;
        let param_idx = self.pgn.fields[start..start + size]
            .iter()
            .enumerate()
            .find(|(_, tf)| tf.field_type == Some(FieldType::FieldIndex))
            .and_then(|(j, _)| match inst[j] {
                Some(Staged::Scalar(n)) => Some(n as u32),
                _ => None,
            })
            .ok_or(unresolved("no staged FIELD_INDEX selects the target field"))?;
        let target_field = target_info
            .fields
            .iter()
            .find(|tf| (tf.order as u32) == param_idx)
            .ok_or(unresolved(
                "FIELD_INDEX is beyond the referenced PGN's fields",
            ))?;
        // A label for a lookup-typed target arrives as Text (the caller
        // cannot know the target's type up front); retype it.
        let is_time = matches!(
            target_field.field_type,
            Some(FieldType::Time) | Some(FieldType::Duration)
        );
        let value = match v {
            EncodeValue::Text(s) if target_field.lookup_enumeration.is_some() => {
                EncodeValue::Lookup(s.clone())
            }
            // A TIME / DURATION target is seconds, as canboat writes it
            // (a whole number too, like any number), and a clock string
            // ("09:10:20.2240") reads as its seconds.
            EncodeValue::Text(s) if is_time => match crate::engine::output::parse_time(s) {
                Some(seconds) => EncodeValue::Number(seconds),
                None => v.clone(),
            },
            other => other.clone(),
        };
        match self.stage_value(target_field, value)? {
            Staged::Scalar(raw) => {
                let bl = target_field
                    .bit_length
                    .ok_or(EncodeError::NotFixedLength(target_field.name))?
                    as usize;
                write_bits(buf, next_bit, bl, raw);
                // The decoder consumes VARIABLE values rounded up to
                // whole bytes. Pad with 0s: that is what canboatjs
                // transmits and what fielded devices have accepted for
                // years - a strict receiver may treat the pad bits as
                // reserved-zero when parsing a command parameter.
                if !next_bit.is_multiple_of(8) {
                    let pad = 8 - (*next_bit % 8);
                    write_bits(buf, next_bit, pad, 0);
                }
            }
            Staged::Bytes(bytes) => {
                for b in bytes {
                    write_bits(buf, next_bit, 8, u64::from(b));
                }
            }
            Staged::Deferred(_) => unreachable!("stage_value never defers"),
        }
        Ok(())
    }

    /// Stage a value for field `f`: strings and binary become byte
    /// payloads (self-describing or fixed-width), everything else a
    /// scalar bit pattern.
    fn stage_value(&self, f: &FieldInfo, v: EncodeValue) -> Result<Staged, EncodeError> {
        match f.field_type {
            Some(FieldType::StringFix) => stage_string_fix(f, v, string_fix_pad(self.pgn.pgn)),
            Some(FieldType::StringLz) => stage_string_lz(f, v),
            Some(FieldType::StringLau) => stage_string_lau(f, v),
            Some(FieldType::Binary) => stage_binary(f, v),
            // DYNAMIC_FIELD_VALUE (the value slot of a key/value PGN like
            // 130845) has no schema `BitLength` — its width is set by the
            // sibling KEY at decode time, so it can't be defaulted, but the
            // caller *can* supply the already-encoded value bytes. Written
            // verbatim (variable length); the caller owns matching the
            // width the resolved key expects. The sibling KEY field is a
            // fixed-width scalar, so it takes the normal `Int` path below.
            Some(FieldType::DynamicFieldValue) => stage_dynamic_value(f, v),
            _ => Ok(Staged::Scalar(self.value_to_raw(f, v)?)),
        }
    }

    /// Convert an [`EncodeValue`] to the raw bit pattern for `f`,
    /// masked/two's-complemented into the field width.
    fn value_to_raw(&self, f: &FieldInfo, v: EncodeValue) -> Result<u64, EncodeError> {
        let bl = f.bit_length.ok_or(EncodeError::NotFixedLength(f.name))?;
        let width = bl + f.continuation.map_or(0, |c| c.bit_length);
        // An integer on a FLOAT is the same value as a Number.
        let v = match (f.field_type, v) {
            (Some(FieldType::Float), EncodeValue::Int(n)) => EncodeValue::Number(n as f64),
            (_, v) => v,
        };
        let raw_i64: i64 = match (f.field_type, v) {
            // Explicit "leave unset".
            (_, EncodeValue::NotAvailable) => return Ok(default_raw(f)),

            // The wire bits, as asked for.
            (_, EncodeValue::Raw(raw)) => return Ok(raw & all_ones(width)),

            // DECIMAL: digit pairs, one byte each, not a binary number.
            (Some(FieldType::Decimal), v) => return decimal_to_raw(f, width, v),

            // Lookup by label → its raw value; or a raw integer.
            (
                Some(FieldType::Lookup) | Some(FieldType::IndirectLookup),
                EncodeValue::Lookup(label),
            ) => self.resolve_lookup(f, &label)? as i64,
            (Some(FieldType::Lookup) | Some(FieldType::IndirectLookup), EncodeValue::Int(n)) => n,

            // BitLookup: a raw bitmask integer (label-per-bit is phase 2).
            (Some(FieldType::BitLookup), EncodeValue::Int(n)) => n,

            // PGN-type: the requested PGN number.
            (Some(FieldType::Pgn), EncodeValue::Pgn(p)) => p as i64,
            (Some(FieldType::Pgn), EncodeValue::Int(n)) => n,

            // FLOAT: IEEE-754 32-bit — the raw bit pattern, not a scaled
            // integer. (The only non-integer scalar wire form.) A Number is
            // in this schema's unit; undo its resolution and unit offset to
            // get the database's unit the wire carries.
            (Some(FieldType::Float), EncodeValue::Number(x)) => {
                let wire = match f.resolution {
                    Some(r) if r != 0.0 => (x - f.unit_offset) / r,
                    _ => x,
                };
                return Ok(u64::from((wire as f32).to_bits()));
            }

            // Text / binary reach `value_to_raw` only on a scalar field
            // (e.g. a string value handed to a NUMBER) — a type error.
            (_, EncodeValue::Text(_)) | (_, EncodeValue::Bytes(_)) => {
                return Err(EncodeError::TypeMismatch {
                    field: f.name,
                    expected: "a numeric value",
                });
            }

            // A PGN number on any field is just a raw integer.
            (_, EncodeValue::Pgn(p)) => p as i64,

            // A physical value, spelled as an integer or not, is inverted
            // through resolution and offsets…
            (Some(t), EncodeValue::Int(n)) if is_scaled(t) => int_to_raw(f, n)?,
            (_, EncodeValue::Number(x)) => scaled_to_raw(f, x)?,
            // …and on every other field an integer is the code itself.
            (_, EncodeValue::Int(n)) => n,

            // A bare Lookup label on a non-lookup field.
            (_, EncodeValue::Lookup(_)) => {
                return Err(EncodeError::TypeMismatch {
                    field: f.name,
                    expected: "a numeric value",
                });
            }
        };
        Ok(mask_to_width(raw_i64, width))
    }

    fn resolve_lookup(&self, f: &FieldInfo, label: &str) -> Result<u64, EncodeError> {
        let table_name = f.lookup_enumeration.ok_or(EncodeError::TypeMismatch {
            field: f.name,
            expected: "a value for a lookup field",
        })?;
        if let Some(table) = self.db.lookup(table_name) {
            for lv in table.values {
                if lv.name == label || lv.id == Some(label) {
                    return Ok(lv.value);
                }
            }
        }
        Err(EncodeError::UnknownLookupLabel {
            field: f.name,
            label: label.to_string(),
        })
    }
}

/// Whether a field's value is a physical quantity, scaled to and from its
/// wire value (as opposed to a code, where the integer is the value).
fn is_scaled(t: FieldType) -> bool {
    matches!(
        t,
        FieldType::Number
            | FieldType::Decimal
            | FieldType::Float
            | FieldType::Date
            | FieldType::Time
            | FieldType::Duration
    )
}

/// An integer value in the field's unit. Taken exactly when the field
/// has no scaling (resolution 1, no offsets), so a 64-bit counter keeps
/// every bit; otherwise scaled like the same [`EncodeValue::Number`].
fn int_to_raw(f: &FieldInfo, n: i64) -> Result<i64, EncodeError> {
    let unscaled =
        f.resolution.unwrap_or(1.0) == 1.0 && f.offset.unwrap_or(0) == 0 && f.unit_offset == 0.0;
    if !unscaled {
        return scaled_to_raw(f, n as f64);
    }
    if let (Some(min), Some(max)) = (f.range_min, f.range_max)
        && ((n as f64) < min || (n as f64) > max)
    {
        return Err(EncodeError::ValueOutOfRange {
            field: f.name,
            value: n as f64,
            range: Some((min, max)),
        });
    }
    Ok(n)
}

/// A DECIMAL's wire bits: each byte holds two decimal digits as a binary
/// value 0..99, the first two digits in the first byte, the inverse of
/// `decode_decimal`.
///
/// The digits are left-justified and padded with zeros on the right. DSC
/// sends a 9-digit MMSI as a 10-digit address with a 0 added at the end
/// (ITU-R M.585), so 512000953 goes out as 5120009530 (#1081). A digit
/// string is taken as written. An integer has lost the leading zeros a
/// group (0MIDXXXXX) or coast station (00MIDXXXX) MMSI starts with, so
/// one shorter than the field is zero-filled on the left to one digit
/// short of it first: 2241024 is coast station 002241024, 0022410240.
fn decimal_to_raw(f: &FieldInfo, width: u32, v: EncodeValue) -> Result<u64, EncodeError> {
    let integer = !matches!(v, EncodeValue::Text(_));
    let digits = match v {
        EncodeValue::Text(s) => s,
        EncodeValue::Int(n) if n >= 0 => n.to_string(),
        EncodeValue::Number(x) if x >= 0.0 && x.fract() == 0.0 && x < 1e19 => {
            (x as u64).to_string()
        }
        EncodeValue::Int(_) | EncodeValue::Number(_) | EncodeValue::Pgn(_) => {
            return Err(EncodeError::TypeMismatch {
                field: f.name,
                expected: "a positive whole number",
            });
        }
        _ => {
            return Err(EncodeError::TypeMismatch {
                field: f.name,
                expected: "decimal digits",
            });
        }
    };
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return Err(EncodeError::TypeMismatch {
            field: f.name,
            expected: "decimal digits",
        });
    }
    let nbytes = width / 8;
    let ndigits = 2 * nbytes as usize;
    let digits = if integer && digits.len() < ndigits {
        format!("{digits:0>w$}", w = ndigits - 1)
    } else {
        digits
    };
    if digits.len() > ndigits {
        return Err(EncodeError::ValueOutOfRange {
            field: f.name,
            value: digits.parse::<f64>().unwrap_or(f64::NAN),
            range: f.range_min.zip(f.range_max),
        });
    }
    let mut raw = 0u64;
    let mut pairs = digits.as_bytes().chunks(2);
    for i in 0..nbytes {
        let pair = match pairs.next() {
            Some([hi, lo]) => (hi - b'0') * 10 + (lo - b'0'),
            Some([hi]) => (hi - b'0') * 10,
            _ => 0,
        };
        raw |= u64::from(pair) << (8 * i);
    }
    Ok(raw)
}

/// Invert the decoder's `raw * resolution + offset + unit_offset`.
/// Mirrors the extraction-signedness quirk: a non-zero schema `offset`
/// forces the field unsigned, so the raw is a plain magnitude.
fn scaled_to_raw(f: &FieldInfo, scaled: f64) -> Result<i64, EncodeError> {
    let scaled = full_turn_angle(f, scaled);
    let resolution = f.resolution.unwrap_or(1.0);
    let display_offset = f.offset.map(|o| o as f64).unwrap_or(0.0);
    let raw = (scaled - f.unit_offset - display_offset) / resolution;
    let rounded = raw.round();
    if !rounded.is_finite() {
        return Err(EncodeError::ValueOutOfRange {
            field: f.name,
            value: scaled,
            range: None,
        });
    }
    // Outside the field's range the raw value would wrap at the field
    // width, or land on a sentinel, and decode as some other value (#970).
    // Compare raw against raw, so a value within half a step of an end
    // still rounds onto it.
    if let (Some(min), Some(max)) = (f.range_min, f.range_max) {
        let raw_of = |v: f64| ((v - f.unit_offset - display_offset) / resolution).round();
        if rounded < raw_of(min) || rounded > raw_of(max) {
            return Err(EncodeError::ValueOutOfRange {
                field: f.name,
                value: scaled,
                range: Some((min, max)),
            });
        }
    }
    Ok(rounded as i64)
}

/// An angle field that covers a full turn (0 to 2 pi rad, 0 to 360 deg)
/// takes a negative angle down to minus half a turn as the same direction:
/// -0.5 rad is 2 pi - 0.5. Signal K and others give a port angle as
/// -pi..0, and before the range check (#970) the wrap at the field width
/// sent those right. Any other value is left as it is.
fn full_turn_angle(f: &FieldInfo, value: f64) -> f64 {
    if f.physical_quantity != Some("ANGLE") || f.range_min != Some(0.0) || value >= 0.0 {
        return value;
    }
    let full = match f.unit {
        Some("rad") => std::f64::consts::TAU,
        Some("deg") => 360.0,
        _ => return value,
    };
    // The top of the range is a step or a rounding short of the full turn.
    match f.range_max {
        Some(max) if max >= full * 0.999 && value >= -full / 2.0 => value + full,
        _ => value,
    }
}

/// The default raw bit pattern for a field the caller left unset.
/// The AIS PGNs with fixed-width text: 129040 Name; 129794 Callsign, Name
/// and Destination; 129809 Name; 129810 Vendor ID and Callsign. Matches
/// canboatjs's `AIS_TEXT_PGNS`, so both encoders send the same bytes.
const AIS_TEXT_PGNS: [u32; 4] = [129040, 129794, 129809, 129810];

/// The byte a `STRING_FIX` field in `pgn` is padded with. AIS pads unused
/// text characters with `@` (6-bit code 0, ITU-R M.1371), and MFDs
/// (Raymarine Axiom, Furuno TZT) show 0xff padding in AIS names as junk.
/// Every other fixed string pads with 0xff, the convention real devices
/// and canboatjs use. The decoder trims NUL, 0xff, `@` and space alike.
fn string_fix_pad(pgn: u32) -> u8 {
    if AIS_TEXT_PGNS.contains(&pgn) {
        b'@'
    } else {
        0xff
    }
}

/// Stage a `STRING_FIX` field: the UTF-8 bytes right-padded with `pad`
/// ([`string_fix_pad`]) to the field's fixed byte width, shortened to fit
/// when the text is longer.
fn stage_string_fix(f: &FieldInfo, v: EncodeValue, pad: u8) -> Result<Staged, EncodeError> {
    let byte_len = f.bit_length.ok_or(EncodeError::NotFixedLength(f.name))? as usize / 8;
    let text = match v {
        EncodeValue::Text(s) => s,
        EncodeValue::NotAvailable => String::new(),
        // Pre-rendered field content, written verbatim at exactly the
        // field width — for callers that must reproduce a specific
        // capture's padding (fixed strings in the wild are padded with
        // 0xff, 0x00 or '@' depending on the device).
        EncodeValue::Bytes(b) => {
            if b.len() != byte_len {
                return Err(EncodeError::ValueOutOfRange {
                    field: f.name,
                    value: b.len() as f64,
                    range: None,
                });
            }
            return Ok(Staged::Bytes(b));
        }
        _ => {
            return Err(EncodeError::TypeMismatch {
                field: f.name,
                expected: "text",
            });
        }
    };
    let bytes = fit_utf8(&text, byte_len).as_bytes();
    let mut buf = vec![pad; byte_len];
    buf[..bytes.len()].copy_from_slice(bytes);
    Ok(Staged::Bytes(buf))
}

/// `s` shortened to at most `max` bytes, cut on a character boundary: a
/// text too long for its string field is truncated rather than refused,
/// and a partial UTF-8 sequence would be read back as Latin-1.
fn fit_utf8(s: &str, max: usize) -> &str {
    if s.len() <= max {
        return s;
    }
    let mut end = max;
    while !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// The text of a string [`EncodeValue`], or an error for the wrong variant.
fn text_of(f: &FieldInfo, v: EncodeValue) -> Result<String, EncodeError> {
    match v {
        EncodeValue::Text(s) => Ok(s),
        EncodeValue::NotAvailable => Ok(String::new()),
        _ => Err(EncodeError::TypeMismatch {
            field: f.name,
            expected: "text",
        }),
    }
}

/// Stage a `STRING_LZ` field: `[length][content][0x00]`, where the length
/// byte counts the content only — what every Fusion device sends, status
/// and commands alike (canboat's `fieldPrintStringLZ` reads the length
/// and content and leaves the NUL). A fixed-width field is `0x00`-padded
/// to its declared byte width. Text too long for the field is shortened
/// so the length byte, content and NUL still fit.
fn stage_string_lz(f: &FieldInfo, v: EncodeValue) -> Result<Staged, EncodeError> {
    let text = text_of(f, v)?;
    let room = match f.bit_length {
        Some(bl) => (bl as usize / 8).saturating_sub(2),
        None => u8::MAX as usize,
    };
    let content = fit_utf8(&text, room.min(u8::MAX as usize)).as_bytes();
    let mut buf = Vec::with_capacity(content.len() + 2);
    buf.push(content.len() as u8);
    buf.extend_from_slice(content);
    buf.push(0);
    if let Some(bl) = f.bit_length {
        buf.resize(bl as usize / 8, 0);
    }
    Ok(Staged::Bytes(buf))
}

/// Stage a `STRING_LAU` field: `[total_len][encoding=1][content]`, where
/// `total_len` counts the two header bytes (canboat's `fieldPrintStringLAU`).
/// Encoding `1` is ASCII/UTF-8. Always variable-length (no padding); text
/// too long for the length byte is shortened.
fn stage_string_lau(f: &FieldInfo, v: EncodeValue) -> Result<Staged, EncodeError> {
    let text = text_of(f, v)?;
    let content = fit_utf8(&text, u8::MAX as usize - 2).as_bytes();
    let mut buf = Vec::with_capacity(content.len() + 2);
    buf.push((content.len() + 2) as u8);
    buf.push(1); // 1 = ASCII / UTF-8
    buf.extend_from_slice(content);
    Ok(Staged::Bytes(buf))
}

/// Stage a `BINARY` field: raw bytes, `0x00`-padded to the declared byte
/// width when the field is fixed-length.
fn stage_binary(f: &FieldInfo, v: EncodeValue) -> Result<Staged, EncodeError> {
    let mut bytes = match v {
        EncodeValue::Bytes(b) => b,
        EncodeValue::NotAvailable => Vec::new(),
        // The bits, little-endian, in the field's whole bytes.
        EncodeValue::Raw(raw) if f.bit_length.is_some_and(|bl| bl <= 64) => {
            let width = f.bit_length.unwrap().div_ceil(8) as usize;
            raw.to_le_bytes()[..width].to_vec()
        }
        _ => {
            return Err(EncodeError::TypeMismatch {
                field: f.name,
                expected: "bytes",
            });
        }
    };
    if let Some(bl) = f.bit_length {
        // Not every BINARY field is byte-aligned (the 19-bit AIS
        // Communication State, for one). A sub-64-bit unaligned width
        // stages as a masked scalar so the packer writes exactly `bl`
        // bits; rendered hex always shows whole bytes, so one extra
        // padding byte is tolerated on the way in.
        if bl % 8 != 0 && bl <= 64 {
            let want = bl.div_ceil(8) as usize;
            if bytes.len() > want {
                return Err(EncodeError::ValueOutOfRange {
                    field: f.name,
                    value: bytes.len() as f64,
                    range: None,
                });
            }
            let mut raw: u64 = 0;
            for (i, b) in bytes.iter().enumerate() {
                raw |= u64::from(*b) << (8 * i);
            }
            raw &= u64::MAX >> (64 - bl);
            return Ok(Staged::Scalar(raw));
        }
        let want = bl as usize / 8;
        if bytes.len() > want {
            return Err(EncodeError::ValueOutOfRange {
                field: f.name,
                value: bytes.len() as f64,
                range: None,
            });
        }
        bytes.resize(want, 0);
    }
    Ok(Staged::Bytes(bytes))
}

/// Stage a `DYNAMIC_FIELD_VALUE` field: the caller-supplied value bytes,
/// written verbatim. Unlike `BINARY` this field carries no declared
/// `BitLength` (its width comes from the resolved sibling KEY), so there
/// is nothing to pad to — the bytes are the value. Only `Bytes` (or an
/// explicit `NotAvailable` → empty) is meaningful here.
fn stage_dynamic_value(f: &FieldInfo, v: EncodeValue) -> Result<Staged, EncodeError> {
    match v {
        EncodeValue::Bytes(b) => Ok(Staged::Bytes(b)),
        EncodeValue::NotAvailable => Ok(Staged::Bytes(Vec::new())),
        _ => Err(EncodeError::TypeMismatch {
            field: f.name,
            expected: "value bytes for a dynamic (key/value) field",
        }),
    }
}

fn default_raw(f: &FieldInfo) -> u64 {
    // A continued field's value includes the high bits another field holds.
    let bl = f.bit_length.unwrap_or(0) + f.continuation.map_or(0, |c| c.bit_length);
    // A variant-selector field: emit the value that identifies this PGN.
    if let Some(mv) = f.match_value {
        return mask_to_width(mv, bl);
    }
    match f.field_type {
        Some(FieldType::Spare) => 0,
        _ => f.unknown_value.unwrap_or_else(|| all_ones(bl)),
    }
}

/// What a `continues:` field holds when the caller left it unset: the high
/// bits of the value staged for the field it continues (or of that field's
/// default), so setting the one field sets both. `None` for any other field.
fn continuing_staged(fields: &[FieldInfo], staged: &[Option<Staged>], j: usize) -> Option<Staged> {
    let target = fields[j].continues?;
    let t = fields[..j].iter().position(|g| g.id == target)?;
    let low = &fields[t];
    let shift = low.bit_length?;
    let value = match &staged[t] {
        Some(Staged::Scalar(v)) => *v,
        None => default_raw(low),
        _ => return None,
    };
    Some(Staged::Scalar(value >> shift))
}

/// Write the "not available" default for a field left unset by the caller.
/// Emit one field: a staged value verbatim, or the field's "not
/// available" default when unset. Shared by the top-level field walk
/// and repeating-set instance emission in [`PgnBuilder::build`].
fn emit_field(
    buf: &mut Vec<u8>,
    next_bit: &mut usize,
    pgn: u32,
    f: &FieldInfo,
    staged: Option<&Staged>,
) -> Result<(), EncodeError> {
    match staged {
        // A string / binary: its packed bytes are written verbatim
        // (byte-aligned — every string/binary field is).
        Some(Staged::Bytes(bytes)) => {
            for &b in bytes {
                write_bits(buf, next_bit, 8, u64::from(b));
            }
            Ok(())
        }
        // A fixed-width scalar (number, lookup, PGN, float, …).
        Some(Staged::Scalar(v)) => {
            let bl = f.bit_length.ok_or(EncodeError::NotFixedLength(f.name))? as usize;
            write_bits(buf, next_bit, bl, *v);
            Ok(())
        }
        // Deferred values are resolved by the instance walk in build();
        // one reaching here means a VARIABLE field outside a repeating
        // set, which the schema does not produce.
        Some(Staged::Deferred(_)) => Err(EncodeError::NotFixedLength(f.name)),
        None => write_unset(buf, next_bit, pgn, f),
    }
}

fn write_unset(
    buf: &mut Vec<u8>,
    next_bit: &mut usize,
    pgn: u32,
    f: &FieldInfo,
) -> Result<(), EncodeError> {
    match f.field_type {
        // Fixed string: all padding (the decoder trims it to an empty
        // string), `@` for AIS text.
        Some(FieldType::StringFix) if f.bit_length.is_some() => {
            for _ in 0..f.bit_length.unwrap() as usize / 8 {
                write_bits(buf, next_bit, 8, u64::from(string_fix_pad(pgn)));
            }
        }
        // Binary: all-1s (binary fields are whole bytes).
        Some(FieldType::Binary) if f.bit_length.is_some() => {
            for _ in 0..f.bit_length.unwrap() as usize / 8 {
                write_bits(buf, next_bit, 8, 0xff);
            }
        }
        // Variable-length binary: nothing to emit.
        Some(FieldType::Binary) => {}
        // Self-describing strings: the minimal empty form.
        Some(FieldType::StringLz) => write_bits(buf, next_bit, 8, 0), // length 0
        Some(FieldType::StringLau) => {
            write_bits(buf, next_bit, 8, 2); // total_len = 2 (header only)
            write_bits(buf, next_bit, 8, 1); // encoding = ASCII/UTF-8
        }
        // The group-function dynamic types take their width/shape from
        // sibling fields at decode time, so they can't be defaulted in
        // isolation — set them explicitly (or use a purpose-built 126208
        // frame).
        Some(FieldType::Variable)
        | Some(FieldType::DynamicFieldKey)
        | Some(FieldType::DynamicFieldLength)
        | Some(FieldType::DynamicFieldValue) => {
            return Err(EncodeError::NotFixedLength(f.name));
        }
        // Every fixed-width scalar: its default at the field's bit width.
        _ => {
            let bl = f.bit_length.ok_or(EncodeError::NotFixedLength(f.name))? as usize;
            write_bits(buf, next_bit, bl, default_raw(f));
        }
    }
    Ok(())
}

/// Two's-complement / mask `value` into `bits` low bits.
fn mask_to_width(value: i64, bits: u32) -> u64 {
    (value as u64) & all_ones(bits)
}

fn all_ones(bits: u32) -> u64 {
    if bits >= 64 {
        u64::MAX
    } else {
        (1u64 << bits) - 1
    }
}

/// Append `bits` low bits of `value`, LSB-first, growing `buf` as needed
/// — the exact layout [`crate::engine::bits::extract_bits`] reads back.
fn write_bits(buf: &mut Vec<u8>, next_bit: &mut usize, bits: usize, mut value: u64) {
    for _ in 0..bits {
        let idx = *next_bit >> 3;
        let bitpos = *next_bit & 7;
        if bitpos == 0 {
            buf.push(0);
        }
        if value & 1 != 0 {
            buf[idx] |= 1 << bitpos;
        }
        value >>= 1;
        *next_bit += 1;
    }
}

/// Coerce a `FIELD=VALUE` string argument per the field's type.
fn coerce_arg(f: &FieldInfo, s: &str) -> Result<EncodeValue, EncodeError> {
    let s = s.trim();
    if s.eq_ignore_ascii_case("n/a") || s.is_empty() {
        return Ok(EncodeValue::NotAvailable);
    }
    // `raw:N` (decimal or 0x-hex) → the wire bits, verbatim.
    if let Some(raw) = s.strip_prefix("raw:") {
        let raw = raw.trim();
        let parsed = match raw.strip_prefix("0x").or_else(|| raw.strip_prefix("0X")) {
            Some(hex) => u64::from_str_radix(hex, 16),
            None => raw.parse::<u64>(),
        };
        return parsed
            .map(EncodeValue::Raw)
            .map_err(|_| EncodeError::ValueOutOfRange {
                field: f.name,
                value: f64::NAN,
                range: None,
            });
    }
    // 0x-hex → an integer, the same as its decimal spelling. Not on a
    // DECIMAL, whose value is its decimal digits.
    if f.field_type != Some(FieldType::Decimal)
        && let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X"))
        && let Ok(n) = i64::from_str_radix(hex, 16)
    {
        return Ok(EncodeValue::Int(n));
    }
    match f.field_type {
        Some(FieldType::Lookup) | Some(FieldType::IndirectLookup) => {
            // Numeric → raw value; otherwise treat as a label.
            match s.parse::<i64>() {
                Ok(n) => Ok(EncodeValue::Int(n)),
                Err(_) => Ok(EncodeValue::Lookup(s.to_string())),
            }
        }
        Some(FieldType::Pgn) => {
            s.parse::<u32>()
                .map(EncodeValue::Pgn)
                .map_err(|_| EncodeError::ValueOutOfRange {
                    field: f.name,
                    value: f64::NAN,
                    range: None,
                })
        }
        Some(FieldType::StringFix)
        | Some(FieldType::StringLz)
        | Some(FieldType::StringLau)
        | Some(FieldType::Variable) => Ok(EncodeValue::Text(s.to_string())),
        // The digits as written, so a leading zero stays.
        Some(FieldType::Decimal) => Ok(EncodeValue::Text(s.to_string())),
        _ => {
            // Numeric field: a value in the field's unit, however it is
            // spelled (`raw:` above asks for wire bits).
            if let Ok(n) = s.parse::<i64>() {
                Ok(EncodeValue::Int(n))
            } else if let Ok(x) = s.parse::<f64>() {
                Ok(EncodeValue::Number(x))
            } else {
                Err(EncodeError::ValueOutOfRange {
                    field: f.name,
                    value: f64::NAN,
                    range: None,
                })
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn db() -> &'static PgnDatabase {
        PgnDatabase::embedded(crate::engine::Units::Metric)
    }

    /// A number outside its field's range is refused, not wrapped at the
    /// field width (#970): 0.3 semi-circles in the 16-bit Inclination
    /// Angle (range about +/-0.0625, 0.196 rad) used to go out as 0.05.
    #[test]
    fn a_number_outside_its_field_range_is_refused() {
        use crate::engine::field::gps_almanac_data::INCLINATION_ANGLE;
        // The field constants describe the SI schema.
        let si = PgnDatabase::embedded(crate::engine::Units::Si);
        let inclination = |v: f64| {
            si.encode_for(crate::engine::pgn::GPS_ALMANAC_DATA)
                .push(INCLINATION_ANGLE, v)
                .map(|_| ())
        };
        let err = inclination(0.3 * std::f64::consts::PI).unwrap_err();
        assert!(matches!(
            err,
            EncodeError::ValueOutOfRange {
                field: "Inclination Angle",
                range: Some((min, max)),
                ..
            } if min < -0.196 && max > 0.196
        ));
        assert!(err.to_string().contains("outside its range"));
        assert!(inclination(-0.3 * std::f64::consts::PI).is_err());
        // Both ends are in range, and so is a value within half a step
        // past one, which rounds onto it.
        let res = INCLINATION_ANGLE.field.resolution.unwrap();
        let max = INCLINATION_ANGLE.field.range_max.unwrap();
        let min = INCLINATION_ANGLE.field.range_min.unwrap();
        inclination(max).unwrap();
        inclination(min).unwrap();
        inclination(max + res * 0.4).unwrap();
        assert!(inclination(max + res).is_err());
    }

    /// A full-turn angle takes a port angle down to minus half a turn as
    /// the same direction, so -pi..pi senders keep working (#970).
    #[test]
    fn a_full_turn_angle_takes_a_negative_angle_as_the_same_direction() {
        use crate::engine::field::wind_data::WIND_ANGLE;
        let si = PgnDatabase::embedded(crate::engine::Units::Si);
        let wind = |v: f64| {
            let mut b = si.encode_for(crate::engine::pgn::WIND_DATA);
            b.push(WIND_ANGLE, v)?;
            Ok::<_, EncodeError>(b.build()?.data[3..5].to_vec())
        };
        let tau = std::f64::consts::TAU;
        assert_eq!(wind(-0.5).unwrap(), wind(tau - 0.5).unwrap());
        assert_eq!(
            wind(-std::f64::consts::PI).unwrap(),
            wind(std::f64::consts::PI).unwrap()
        );
        // Past half a turn back, or a full turn forward, is still refused.
        assert!(wind(-3.2).is_err());
        assert!(wind(tau + 0.1).is_err());
    }

    /// A DECIMAL goes out as digit pairs and decodes back to the same
    /// digits (#1081), where it used to go out as a binary number that
    /// decoded as not available.
    #[test]
    fn a_decimal_is_digit_pairs_and_round_trips() {
        use crate::engine::decode::FieldValue;
        let address = |v: &str| {
            let mut b = db().encode_for(crate::engine::pgn::DSC_CALL_INFORMATION);
            b.push_arg("dscMessageAddress", v)?;
            b.build()
        };
        let decoded = |v: &str| {
            let frame = address(v).unwrap();
            let decoded = db().decode(&frame).unwrap();
            let f = decoded
                .fields
                .iter()
                .find(|f| f.id() == "dscMessageAddress");
            (frame.data[2..7].to_vec(), f.map(|f| f.value.clone()))
        };

        // Ten digits, a leading zero kept.
        let (wire, value) = decoded("0244123456");
        assert_eq!(wire, [2, 44, 12, 34, 56]);
        assert!(matches!(value, Some(FieldValue::Decimal(d)) if d == "0244123456"));
        // A 9-digit MMSI takes a trailing zero, as DSC sends it, and comes
        // back without it, as the MMSI.
        let (wire, value) = decoded("244060807");
        assert_eq!(wire, [24, 40, 60, 80, 70]);
        assert!(matches!(value, Some(FieldValue::Decimal(d)) if d == "244060807"));
        // The coast station in samples/pgn129808.raw: its leading zeros
        // are part of the MMSI.
        let (wire, value) = decoded("002241024");
        assert_eq!(wire, [0, 22, 41, 2, 40]);
        assert!(matches!(value, Some(FieldValue::Decimal(d)) if d == "002241024"));
        // An integer has lost those zeros, so it is filled out to the 9
        // digits of an MMSI first; ten digits are the whole address.
        let int = |n: i64| {
            let mut b = db().encode_for(crate::engine::pgn::DSC_CALL_INFORMATION);
            b.push_by_name("DSC Message Address", n).unwrap();
            b.build().unwrap().data[2..7].to_vec()
        };
        assert_eq!(int(244123456), [24, 41, 23, 45, 60]);
        assert_eq!(int(2241024), [0, 22, 41, 2, 40]);
        assert_eq!(int(2241024000), [22, 41, 2, 40, 0]);

        // Too many digits, or not digits at all, is refused.
        assert!(matches!(
            address("12345678901"),
            Err(EncodeError::ValueOutOfRange { .. })
        ));
        assert!(matches!(
            address("12ab"),
            Err(EncodeError::TypeMismatch { .. })
        ));
        assert!(matches!(
            address("0x12"),
            Err(EncodeError::TypeMismatch { .. })
        ));
        // raw: still writes the wire bits.
        assert_eq!(address("raw:0xffffffffff").unwrap().data[2..7], [0xff; 5]);
    }

    #[test]
    fn iso_request_matches_c_format_message() {
        // The canboat `format-message` example: request Product Info
        // (126996 = 0x1F014) → PGN 59904, data 14 f0 01.
        let frame = db()
            .encode_for(crate::engine::pgn::ISO_REQUEST)
            .priority(6)
            .destination(255)
            .push(crate::engine::field::iso_request::PGN, 126996u32)
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(frame.pgn, 59904);
        assert_eq!(frame.prio, 6);
        assert_eq!(frame.dst, 255);
        assert_eq!(frame.data.as_slice(), &[0x14, 0xf0, 0x01]);
    }

    /// J1939 temperatures are exact: -40 C is raw 0 of an 8-bit field, 1 K
    /// per bit from 233.15 K, and 100 C is raw 11936 of a 16-bit one,
    /// 0.03125 K per bit from 0.15 K. In SI and in Metric.
    #[test]
    fn j1939_temperatures_encode_exactly() {
        use crate::engine::Units;
        for (units, coolant, fuel, oil) in [
            (Units::Si, 323.15, 233.15, 373.15),
            (Units::Metric, 50.0, -40.0, 100.0),
        ] {
            let db = PgnDatabase::embedded_j1939(units);
            let mut b = db.encode_by_pgn(65262).unwrap();
            b.push_by_name("Engine Coolant Temp", coolant)
                .unwrap()
                .push_by_name("Engine Fuel Temp 1", fuel)
                .unwrap()
                .push_by_name("Engine Oil Temp 1", oil)
                .unwrap();
            let frame = b.build().unwrap();
            assert_eq!(&frame.data[..4], &[90, 0, 0xa0, 0x2e], "{units:?}");
        }
    }

    /// A J1939 DM1 trouble code's SPN is split around the FMI (J1939-73).
    /// Setting the one `spn` field writes both halves; decoding joins them
    /// and names the SPN, and the high-bits field stays out of the output.
    #[test]
    fn a_dm1_spn_is_split_on_encode_and_joined_on_decode() {
        use crate::engine::decode::FieldValue;
        let db = PgnDatabase::embedded_j1939(crate::engine::Units::Si);
        let dtc = |spn: EncodeValue| {
            let mut b = db.encode_by_pgn(65226).unwrap();
            let i = b.add_set_instance(1).unwrap();
            b.push_in_set(1, i, "spn", spn)
                .unwrap()
                .push_in_set(1, i, "fmi", 2u32)
                .unwrap()
                .push_in_set(1, i, "oc", 5u32)
                .unwrap()
                .push_in_set(1, i, "cm", 0u32)
                .unwrap();
            b.build().unwrap()
        };

        // 520192 = 0xf000 + 7 << 16: the 7 lands above the FMI's 5 bits.
        let frame = dtc(EncodeValue::Int(520192));
        assert_eq!(&frame.data[2..6], &[0x00, 0xf0, 0xe2, 0x05]);
        let decoded = db.decode(&frame).unwrap();
        let spn = decoded.fields.iter().find(|f| f.id() == "spn").unwrap();
        assert!(matches!(
            spn.value,
            FieldValue::Lookup {
                value: 520192,
                name: None
            }
        ));
        assert!(decoded.fields.iter().all(|f| f.id() != "spnHigh"));

        // Cut short inside the low SPN bits: the byte that is there is not
        // the SPN, so there is none, as the C decodes it.
        let mut short = frame.clone();
        short.data.truncate(3);
        let decoded = db.decode(&short).unwrap();
        assert!(
            decoded.fields.iter().all(|f| f.id() != "spn"),
            "a cut-off SPN is left out"
        );

        // A name from the SPN lookup encodes as its number.
        let frame = dtc(EncodeValue::Lookup("Engine Oil Pressure".into()));
        assert_eq!(&frame.data[2..6], &[0x64, 0x00, 0x02, 0x05]);
        let decoded = db.decode(&frame).unwrap();
        let spn = decoded.fields.iter().find(|f| f.id() == "spn").unwrap();
        assert!(matches!(
            spn.value,
            FieldValue::Lookup {
                value: 100,
                name: Some("Engine Oil Pressure")
            }
        ));
    }

    #[test]
    fn ambiguous_pgn_number_is_rejected() {
        // 59904 is unique; 126208 (group function) has several variants.
        assert!(db().encode_by_pgn(59904).is_ok());
        assert!(matches!(
            db().encode_by_pgn(126208),
            Err(EncodeError::AmbiguousPgn { pgn: 126208, .. })
        ));
    }

    #[test]
    fn unset_fields_default_and_length_checks() {
        // Encoding with no fields set still produces a schema-length
        // frame (defaults fill in), and match_value selector fields are
        // auto-populated so the variant stays valid.
        let frame = db().encode_for(crate::engine::pgn::ISO_REQUEST).build();
        // isoRequest has a single PGN field with no match_value; unset →
        // not-available (all ones), 3 bytes.
        let f = frame.unwrap();
        assert_eq!(f.data.len(), 3);
        assert_eq!(f.data.as_slice(), &[0xff, 0xff, 0xff]);
    }

    #[test]
    fn wind_data_round_trips_through_decode() {
        // The real invariant: decode(encode(x)) == x. Encode a scaled
        // number, an integer, and a lookup-by-label, then decode the
        // frame back and compare physical values (unit-agnostic — the
        // compiled schema may store angles in degrees, etc.).
        use crate::engine::field::wind_data as wd;
        let db = db();
        let frame = db
            .encode_for(crate::engine::pgn::WIND_DATA)
            .push(wd::SID, 7)
            .unwrap()
            .push(wd::WIND_SPEED, 5.23)
            .unwrap()
            .push(wd::WIND_ANGLE, 1.5)
            .unwrap()
            // The lookup *label* stays a string — value-name constants are
            // out of scope for now.
            .push(wd::REFERENCE, EncodeValue::Lookup("Apparent".into()))
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(frame.pgn, 130306);
        assert_eq!(frame.data.len(), 8);

        let decoded = db.decode(&frame).unwrap();
        assert_eq!(decoded.id, "windData");

        let num = |name: &str| match &decoded.field_by_name(name).unwrap().value {
            crate::engine::FieldValue::Number(x) => *x,
            crate::engine::FieldValue::Integer(n) => *n as f64,
            other => panic!("field {name}: expected a number, got {other:?}"),
        };
        // Within a resolution step (rounding on the way in).
        assert!((num("Wind Speed") - 5.23).abs() < 0.01);
        assert!((num("Wind Angle") - 1.5).abs() < 0.01);
        assert_eq!(num("SID"), 7.0);

        match &decoded.field_by_name("Reference").unwrap().value {
            crate::engine::FieldValue::Lookup { value, name } => {
                assert_eq!(*value, 2);
                assert_eq!(*name, Some("Apparent"));
            }
            other => panic!("Reference: expected lookup, got {other:?}"),
        }
    }

    #[test]
    fn repeating_set_round_trips_through_decode() {
        // 129540 GNSS Sats in View: fixed prefix (sid, mode, reserved,
        // count) then N × {prn, elevation, azimuth, snr, residuals,
        // status}. Stage two instances, leave the count field unset (it
        // must auto-fill with 2), decode the frame back and compare the
        // per-iteration values.
        let db = db();
        let mut b = db.encode("gnssSatsInView").unwrap();
        b.push_by_name("SID", 9).unwrap();
        for (prn, snr) in [(7i64, 30.0f64), (11, 42.5)] {
            let i = b.add_set_instance(1).unwrap();
            b.push_in_set(1, i, "PRN", prn).unwrap();
            b.push_in_set(1, i, "SNR", snr).unwrap();
        }
        let frame = b.build().unwrap();
        assert_eq!(frame.pgn, 129540);

        let decoded = db.decode(&frame).unwrap();
        assert!(decoded.has_repeating_set[0]);
        let count = match &decoded.field_by_name("Sats in View").unwrap().value {
            crate::engine::FieldValue::Integer(n) => *n,
            crate::engine::FieldValue::Number(x) => *x as i64,
            other => panic!("Sats in View: expected a number, got {other:?}"),
        };
        assert_eq!(count, 2, "count field must auto-fill from instances");

        let per_iter = |id: &str| -> Vec<f64> {
            decoded
                .fields
                .iter()
                .filter(|f| f.info.id == id && f.repeat_set == 1)
                .map(|f| match &f.value {
                    crate::engine::FieldValue::Integer(n) => *n as f64,
                    crate::engine::FieldValue::Number(x) => *x,
                    other => panic!("{id}: expected a number, got {other:?}"),
                })
                .collect()
        };
        assert_eq!(per_iter("prn"), vec![7.0, 11.0]);
        let snrs = per_iter("snr");
        assert_eq!(snrs.len(), 2);
        assert!((snrs[0] - 30.0).abs() < 0.01);
        assert!((snrs[1] - 42.5).abs() < 0.01);
    }

    #[test]
    fn repeating_set_errors() {
        let db = db();
        // windData has no repeating sets.
        assert!(matches!(
            db.encode("windData").unwrap().add_set_instance(1),
            Err(EncodeError::NoRepeatingSet { set: 1, .. })
        ));
        // An instance index that was never added is rejected.
        assert!(matches!(
            db.encode("gnssSatsInView")
                .unwrap()
                .push_in_set(1, 0, "PRN", 1),
            Err(EncodeError::NoSuchInstance { instance: 0, .. })
        ));
    }

    #[test]
    fn group_function_variable_values_encode_via_the_referenced_pgn() {
        // A 126208 Command Group Function for PGN 127250 (Vessel
        // Heading): parameter 2 is the Heading field, whose width
        // (16 bits) and resolution (1e-4 rad) live in 127250, not in
        // 126208. The deferred VARIABLE path must resolve them.
        let db = db();
        let mut b = db.encode("nmeaCommandGroupFunction").unwrap();
        b.push_by_name("PGN", EncodeValue::Pgn(127250)).unwrap();
        let heading_order = db
            .first_pgn(127250)
            .unwrap()
            .fields
            .iter()
            .find(|f| f.id == "heading")
            .unwrap()
            .order as i64;
        let i = b.add_set_instance(1).unwrap();
        b.push_in_set(1, i, "Parameter", heading_order).unwrap();
        b.push_in_set(1, i, "Value", 1.5f64).unwrap();
        let frame = b.build().map_err(|e| format!("{e}")).unwrap();
        assert_eq!(frame.pgn, 126208);

        let decoded = db.decode(&frame).unwrap();
        let val = decoded
            .fields
            .iter()
            .find(|f| f.repeat_set == 1 && f.info.field_type == Some(FieldType::Variable))
            .expect("decoded VARIABLE value");
        match &val.value {
            crate::engine::FieldValue::Number(x) => assert!((x - 1.5).abs() < 0.01, "got {x}"),
            crate::engine::FieldValue::Integer(n) => {
                assert!((*n as f64 - 1.5).abs() < 1.0, "got {n}")
            }
            other => panic!("value: {other:?}"),
        }
    }

    #[test]
    fn variable_target_variant_follows_the_parameter_pairs() {
        // A 126208 Command for PGN 130833, which has three variants:
        // Maretron (listed first), B&G, Furuno. The pairs set
        // Manufacturer=1855/Industry=4, so parameter 5 must use the
        // *Furuno* variant's field 5 — Antenna position X, 16 bits at
        // 0.01 — and not Maretron's Memory Capacity (64 bits at 1),
        // which resolving the leading definition blindly would give.
        // Decode already matches the variant from the pairs (the C's
        // getMatchingPgnByParameters), so without this the encoder
        // produced frames its own decoder mis-read.
        let db = db();
        let mut b = db.encode("nmeaCommandGroupFunction").unwrap();
        b.push_by_name("PGN", EncodeValue::Pgn(130833)).unwrap();
        for (param, value) in [(1i64, 1855f64), (3, 4.0), (5, 3.21)] {
            let i = b.add_set_instance(1).unwrap();
            b.push_in_set(1, i, "Parameter", param).unwrap();
            b.push_in_set(1, i, "Value", value).unwrap();
        }
        let frame = b.build().map_err(|e| format!("{e}")).unwrap();
        // 6 header bytes + (1,manufacturer 11b→2) + (3,industry 3b→1)
        // + (5, 16b→2) pairs = 14 bytes; the Maretron mis-resolution
        // would stretch parameter 5 to 8 bytes (20 total).
        assert_eq!(frame.data.len(), 14, "data: {:02x?}", frame.data);
        // 3.21 at the Furuno resolution of 0.01 → raw 321, LE.
        assert_eq!(
            &frame.data[12..],
            &[0x41, 0x01],
            "data: {:02x?}",
            frame.data
        );

        // Round-trip: the decoder picks the variant independently from
        // the wire bytes and must recover the commanded value.
        let decoded = db.decode(&frame).unwrap();
        let val = decoded
            .fields
            .iter()
            .rfind(|f| f.repeat_set == 1 && f.info.field_type == Some(FieldType::Variable))
            .expect("decoded VARIABLE value");
        match &val.value {
            crate::engine::FieldValue::Number(x) => assert!((x - 3.21).abs() < 0.005, "got {x}"),
            other => panic!("value: {other:?}"),
        }
    }

    #[test]
    fn variable_target_without_narrowing_pairs_keeps_the_leading_definition() {
        // A proprietary multi-variant target commanded without leading
        // Manufacturer/Industry pairs cannot be narrowed; the encoder
        // must fall back to the leading definition exactly as before
        // (Maretron's Memory Capacity: 64 bits at resolution 1).
        let db = db();
        let mut b = db.encode("nmeaCommandGroupFunction").unwrap();
        b.push_by_name("PGN", EncodeValue::Pgn(130833)).unwrap();
        let i = b.add_set_instance(1).unwrap();
        b.push_in_set(1, i, "Parameter", 5i64).unwrap();
        b.push_in_set(1, i, "Value", 3f64).unwrap();
        let frame = b.build().map_err(|e| format!("{e}")).unwrap();
        // 6 header bytes + param byte + 64-bit value.
        assert_eq!(frame.data.len(), 15, "data: {:02x?}", frame.data);
        assert_eq!(frame.data[7], 3, "data: {:02x?}", frame.data);
    }

    #[test]
    fn variable_without_target_is_a_clear_error() {
        let db = db();
        let mut b = db.encode("nmeaCommandGroupFunction").unwrap();
        let i = b.add_set_instance(1).unwrap();
        b.push_in_set(1, i, "Value", 1i64).unwrap();
        assert!(matches!(
            b.build(),
            Err(EncodeError::VariableUnresolved { .. })
        ));
    }

    #[test]
    fn unknown_lookup_label_is_rejected() {
        assert!(matches!(
            db().encode("windData")
                .unwrap()
                .push_by_name("Reference", EncodeValue::Lookup("Nonsense".into())),
            Err(EncodeError::UnknownLookupLabel { .. })
        ));
    }

    #[test]
    fn no_such_field_and_pgn() {
        assert!(matches!(
            db().encode("isoRequest").unwrap().push_by_name("Nope", 1),
            Err(EncodeError::NoSuchField { .. })
        ));
        assert!(matches!(
            db().encode("notAPgnId"),
            Err(EncodeError::NoSuchPgnId(_))
        ));
    }

    #[test]
    fn string_fix_round_trips() {
        use crate::engine::field::product_information::MODEL_ID;
        let frame = db()
            .encode("productInformation")
            .unwrap()
            .push(MODEL_ID, "SCX-20")
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        assert_eq!(
            d.field(MODEL_ID).and_then(|f| f.value.as_str()),
            Some("SCX-20")
        );
    }

    /// AIS text pads with '@' (ITU-R M.1371), as canboatjs does: MFDs
    /// show 0xff padding in AIS names as junk.
    #[test]
    fn ais_text_is_padded_with_at_signs() {
        use crate::engine::field::ais_class_bstatic_data_msg24_part_a::NAME;
        let frame = db()
            .encode("aisClassBStaticDataMsg24PartA")
            .unwrap()
            .push(NAME, "MERRIMAC")
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(&frame.data[5..25], b"MERRIMAC@@@@@@@@@@@@");
        let d = db().decode(&frame).unwrap();
        assert_eq!(
            d.field(NAME).and_then(|f| f.value.as_str()),
            Some("MERRIMAC")
        );
    }

    /// Unset AIS text is all '@' too, in every PGN of the set.
    #[test]
    fn unset_ais_text_is_all_at_signs() {
        let frame = db()
            .encode("aisClassBStaticDataMsg24PartB")
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(&frame.data[6..20], &[b'@'; 14], "Vendor ID and Callsign");
        for pgn in AIS_TEXT_PGNS {
            let info = db().pgns().find(|p| p.pgn == pgn).unwrap();
            let frame = db().encode(info.id).unwrap().build().unwrap();
            let mut offset = 0;
            for f in info.fields {
                let bits = f.bit_length.unwrap_or(0) as usize;
                if f.field_type == Some(FieldType::StringFix) {
                    let text = &frame.data[offset / 8..(offset + bits) / 8];
                    assert!(
                        text.iter().all(|&b| b == b'@'),
                        "{pgn} {}: {text:?}",
                        f.name
                    );
                }
                offset += bits;
            }
        }
    }

    /// Fixed strings outside AIS keep the 0xff padding.
    #[test]
    fn other_fixed_strings_are_padded_with_0xff() {
        use crate::engine::field::product_information::MODEL_ID;
        let frame = db()
            .encode("productInformation")
            .unwrap()
            .push(MODEL_ID, "SCX-20")
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(&frame.data[4..10], b"SCX-20");
        assert!(frame.data[10..36].iter().all(|&b| b == 0xff));
    }

    #[test]
    fn string_lau_round_trips() {
        use crate::engine::field::configuration_information::INSTALLATION_DESCRIPTION1 as DESC1;
        let frame = db()
            .encode("configurationInformation")
            .unwrap()
            .push(DESC1, "Helm Station")
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        assert_eq!(
            d.field(DESC1).and_then(|f| f.value.as_str()),
            Some("Helm Station")
        );
    }

    #[test]
    fn string_lz_round_trips() {
        use crate::engine::field::navico_ascii_identifier::IDENTIFIER;
        let frame = db()
            .encode("navicoAsciiIdentifier")
            .unwrap()
            .push(IDENTIFIER, "BOW")
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        assert_eq!(
            d.field(IDENTIFIER).and_then(|f| f.value.as_str()),
            Some("BOW")
        );
    }

    #[test]
    fn string_lz_is_written_as_fusion_sends_it() {
        // A Fusion MS-RA70N Set Zone Name, sent by an MFD (canboat's
        // samples/fusion-ms-ra70n-zone-controls.raw): the length byte
        // counts the content, and a NUL follows it.
        use crate::engine::field::fusion_set_zone_name::{NAME, ZONE};
        let frame = db()
            .encode("fusionSetZoneName")
            .unwrap()
            .push(ZONE, 0.0)
            .unwrap()
            .push(NAME, "COCKPIT")
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(
            frame.data.as_slice(),
            &[
                0xa3, 0x99, 0x22, 0x00, 0x00, 0x07, b'C', b'O', b'C', b'K', b'P', b'I', b'T', 0x00
            ]
        );
    }

    #[test]
    fn a_fixed_width_string_lz_keeps_room_for_its_nul() {
        // Fusion RDS Data's text is a 32-byte STRING_LZ: at most 30 bytes
        // of content, then the NUL, then zero padding.
        use crate::engine::field::fusion_rds_data::RDS;
        let long = "x".repeat(40);
        let frame = db()
            .encode("fusionRdsData")
            .unwrap()
            .push(RDS, long.as_str())
            .unwrap()
            .build()
            .unwrap();
        let tail = &frame.data[frame.data.len() - 32..];
        assert_eq!(tail[0], 30);
        assert_eq!(&tail[1..31], "x".repeat(30).as_bytes());
        assert_eq!(tail[31], 0);
    }

    #[test]
    fn too_long_strings_are_shortened_not_refused() {
        // STRING_FIX: Product Information's Model ID is 32 bytes. The cut
        // never splits a character: 'é' is two bytes and would straddle it.
        use crate::engine::field::product_information::MODEL_ID;
        let text = format!("{}é", "a".repeat(31));
        let frame = db()
            .encode("productInformation")
            .unwrap()
            .push(MODEL_ID, text.as_str())
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        assert_eq!(
            d.field(MODEL_ID).and_then(|f| f.value.as_str()),
            Some("a".repeat(31).as_str())
        );

        // STRING_LAU: the length byte counts itself and the control byte,
        // so 253 bytes of content is the most it can carry.
        use crate::engine::field::configuration_information::INSTALLATION_DESCRIPTION1 as DESC1;
        let frame = db()
            .encode("configurationInformation")
            .unwrap()
            .push(DESC1, "y".repeat(300).as_str())
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        assert_eq!(
            d.field(DESC1).and_then(|f| f.value.as_str()).map(str::len),
            Some(253)
        );
    }

    #[test]
    fn binary_round_trips() {
        // A fixed-width (7-byte) BINARY field: a full-width payload round-
        // trips exactly (a shorter one would be 0x00-padded to the width).
        use crate::engine::field::iso_transport_protocol_data_transfer::DATA;
        let payload = vec![0xde_u8, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03];
        let frame = db()
            .encode("isoTransportProtocolDataTransfer")
            .unwrap()
            .push(DATA, payload.clone())
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        match d.field(DATA).map(|f| &f.value) {
            Some(crate::engine::FieldValue::Binary(v)) => assert_eq!(v, &payload),
            other => panic!("expected binary, got {other:?}"),
        }
    }

    #[test]
    fn float_round_trips() {
        // FLOAT is written as raw IEEE-754 bits (no resolution scaling),
        // so it survives a round-trip within f32 precision.
        use crate::engine::field::garmin_autopilot_heading_to_steer::HEADING_TO_STEER as HTS;
        let frame = db()
            .encode("garminAutopilotHeadingToSteer")
            .unwrap()
            .push(HTS, 1.5)
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        let got = d.field(HTS).and_then(|f| f.value.as_f64()).unwrap();
        assert!((got - 1.5).abs() < 1e-6, "got {got}");
    }

    /// An integer is a value in the field's unit, like the same number
    /// written as a float (#981): 5 m/s is not 0.05 m/s, 300 K not 3 K.
    #[test]
    fn an_integer_is_a_value_in_the_fields_unit() {
        use crate::engine::field::temperature::ACTUAL_TEMPERATURE;
        use crate::engine::field::wind_data::{REFERENCE, WIND_SPEED};
        let si = PgnDatabase::embedded(crate::engine::Units::Si);
        let wind = |v: EncodeValue| {
            si.encode_for(crate::engine::pgn::WIND_DATA)
                .push(WIND_SPEED, v)
                .unwrap()
                .build()
                .unwrap()
                .data
        };
        assert_eq!(wind(5.into()), wind(5.0.into()));
        let temperature = |v: EncodeValue| {
            si.encode_for(crate::engine::pgn::TEMPERATURE)
                .push(ACTUAL_TEMPERATURE, v)
                .unwrap()
                .build()
                .unwrap()
        };
        let frame = temperature(300.into());
        assert_eq!(frame.data, temperature(300.0.into()).data);
        let d = si.decode(&frame).unwrap();
        let got = d.field(ACTUAL_TEMPERATURE).and_then(|f| f.value.as_f64());
        assert!((got.unwrap() - 300.0).abs() < 1e-9, "{got:?}");
        // On a lookup the integer is the code.
        let frame = si
            .encode_for(crate::engine::pgn::WIND_DATA)
            .push(REFERENCE, 2)
            .unwrap()
            .build()
            .unwrap();
        let d = si.decode(&frame).unwrap();
        assert_eq!(
            d.field(REFERENCE).and_then(|f| f.value.as_str()),
            Some("Apparent")
        );
    }

    /// A signed field reaches the full negative end of its bits: NMEA 2000
    /// reserves sentinels at the top only, so -3276.8 A (raw -32768) is a
    /// value, and a step below it is refused.
    #[test]
    fn a_signed_field_takes_its_full_negative_end() {
        use crate::engine::field::battery_status::CURRENT;
        let si = PgnDatabase::embedded(crate::engine::Units::Si);
        let current = |a: f64| {
            si.encode_for(crate::engine::pgn::BATTERY_STATUS)
                .push(CURRENT, a)
                .and_then(|b| b.build())
        };
        let frame = current(-3276.8).unwrap();
        assert_eq!(&frame.data[3..5], &[0x00, 0x80]);
        let d = si.decode(&frame).unwrap();
        let got = d.field(CURRENT).and_then(|f| f.value.as_f64()).unwrap();
        assert!((got + 3276.8).abs() < 1e-9, "{got}");
        assert!(matches!(
            current(-3276.9),
            Err(EncodeError::ValueOutOfRange { .. })
        ));
    }

    /// `Raw` writes the wire bits verbatim, a sentinel included, where an
    /// integer outside the field's range is refused like any number.
    #[test]
    fn raw_writes_the_wire_bits() {
        use crate::engine::field::temperature::{ACTUAL_TEMPERATURE, INSTANCE};
        let si = PgnDatabase::embedded(crate::engine::Units::Si);
        let b = || si.encode_for(crate::engine::pgn::TEMPERATURE);
        assert!(matches!(
            b().push(INSTANCE, 255),
            Err(EncodeError::ValueOutOfRange { .. })
        ));
        let frame = b()
            .push(INSTANCE, Raw(255))
            .unwrap()
            .push(ACTUAL_TEMPERATURE, Raw(0x7531))
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(frame.data[1], 255);
        assert_eq!(&frame.data[3..5], &[0x31, 0x75]);
        // Wider than the field: masked to its width.
        let frame = b().push(INSTANCE, Raw(0x1_23)).unwrap().build().unwrap();
        assert_eq!(frame.data[1], 0x23);
    }

    /// An integer on an unscaled 64-bit field keeps every bit, beyond
    /// what an f64 holds.
    #[test]
    fn an_unscaled_integer_is_exact() {
        let f = FieldInfo {
            resolution: Some(1.0),
            range_min: None,
            range_max: None,
            ..db()
                .pgns()
                .flat_map(|p| p.fields)
                .find(|f| f.field_type == Some(FieldType::Number) && f.bit_length == Some(64))
                .copied()
                .unwrap()
        };
        let n = (1i64 << 60) + 1;
        assert_eq!(int_to_raw(&f, n).unwrap(), n);
    }

    #[test]
    fn format_message_spells_raw_explicitly() {
        use crate::engine::field::wind_data::{REFERENCE, WIND_SPEED};
        let speed = WIND_SPEED.field;
        assert_eq!(coerce_arg(speed, "5").unwrap(), EncodeValue::Int(5));
        assert_eq!(coerce_arg(speed, "0x5").unwrap(), EncodeValue::Int(5));
        assert_eq!(coerce_arg(speed, "5.0").unwrap(), EncodeValue::Number(5.0));
        assert_eq!(
            coerce_arg(speed, "raw:0xffff").unwrap(),
            EncodeValue::Raw(0xffff)
        );
        assert_eq!(coerce_arg(speed, "raw:500").unwrap(), EncodeValue::Raw(500));
        assert!(coerce_arg(speed, "raw:-1").is_err());
        assert_eq!(
            coerce_arg(REFERENCE.field, "2").unwrap(),
            EncodeValue::Int(2)
        );
    }

    #[test]
    fn iso_name_round_trips() {
        // A NAME with the top (arbitrary-address-capable) bit set exercises
        // the full u64 range that an i64 alone couldn't express.
        use crate::engine::field::simnet_data_source_selection::SOURCE;
        let name: u64 = 0xC078_8C00_E7E0_4364;
        let frame = db()
            .encode("simnetDataSourceSelection")
            .unwrap()
            .push(SOURCE, Raw(name))
            .unwrap()
            .build()
            .unwrap();
        let d = db().decode(&frame).unwrap();
        match d.field(SOURCE).map(|f| &f.value) {
            Some(crate::engine::FieldValue::IsoName { value, .. }) => assert_eq!(*value, name),
            other => panic!("expected iso name, got {other:?}"),
        }
    }

    #[test]
    fn simnet_key_value_encodes_key_and_value() {
        // PGN 130845 simnetKeyValue is a key/value PGN: the KEY is a
        // fixed 24-bit DYNAMIC_FIELD_KEY (an integer: the key code) and the VALUE
        // is a DYNAMIC_FIELD_VALUE whose bytes are written verbatim. This
        // is the frame merrimac sends to set Simrad display night mode
        // (key 9983, value 0x04).
        let frame = db()
            .encode("simnetKeyValue")
            .unwrap()
            .destination(255)
            .push_by_name("Address", EncodeValue::Int(255))
            .unwrap()
            .push_by_name("Instance", Raw(255))
            .unwrap()
            .push_by_name("Network Group", EncodeValue::Int(1))
            .unwrap()
            .push_by_name("Source", Raw(255))
            .unwrap()
            .push_by_name("Key", EncodeValue::Int(9983))
            .unwrap()
            .push_by_name("Operation", EncodeValue::Int(1))
            .unwrap()
            .push_by_name("Value", EncodeValue::Bytes(vec![0x04]))
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(frame.pgn, 130845);
        // 6 header bytes (11+2+3+8+8+8+8 = 48 bits) + 3 key + 1 op + 1 value.
        assert_eq!(frame.data.len(), 11);
        // Manufacturer Code (match 1857) + Industry Code (match 4) auto-fill.
        // Key 9983 = 0x26FF, little-endian 24-bit at bytes 6..9.
        assert_eq!(&frame.data[6..9], &[0xff, 0x26, 0x00]);
        assert_eq!(frame.data[9], 0x01); // Operation = Set
        assert_eq!(frame.data[10], 0x04); // Value byte, verbatim
    }

    #[test]
    fn dynamic_field_value_rejects_non_bytes() {
        // The value slot has no declared width; a scalar can't be sized.
        assert!(matches!(
            db().encode("simnetKeyValue")
                .unwrap()
                .push_by_name("Value", EncodeValue::Int(4)),
            Err(EncodeError::TypeMismatch { .. })
        ));
    }

    #[test]
    fn dynamic_group_function_field_is_a_clear_error() {
        // The 126208 group-function dynamic types can't be defaulted in
        // isolation; an unset one inside a staged parameter pair is a
        // descriptive error, not wrong bytes.
        let mut b = db().encode("nmeaRequestGroupFunction").unwrap();
        b.add_set_instance(1).unwrap();
        let err = b.build();
        assert!(
            matches!(err, Err(EncodeError::NotFixedLength(_))),
            "got {err:?}"
        );
    }

    #[test]
    fn zero_instance_repeating_pgn_builds_with_zero_count() {
        // A bare group-function request is a legitimate zero-parameter
        // message: the repeating set is absent from the payload and the
        // count field auto-fills with 0 (a real count, not
        // "unavailable"). The repeating fields' dynamic widths never
        // come into play.
        let frame = db()
            .encode("nmeaRequestGroupFunction")
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(frame.pgn, 126208);
        let decoded = db().decode(&frame).unwrap();
        match &decoded
            .field_by_name("Number of Parameters")
            .expect("count field decoded")
            .value
        {
            crate::engine::FieldValue::Integer(n) => assert_eq!(*n, 0),
            crate::engine::FieldValue::Number(x) => assert_eq!(*x, 0.0),
            other => panic!("count: expected a number, got {other:?}"),
        }
    }

    /// A 126208 Write Fields commanding `pgn`, with one selection pair
    /// and one parameter, header fields left to the caller.
    fn write_fields(pgn: u32) -> PgnBuilder {
        let mut b = db().encode("nmeaWriteFieldsGroupFunction").unwrap();
        b.push_by_name("PGN", EncodeValue::Pgn(pgn)).unwrap();
        b.push_by_name("Unique ID", 0i64).unwrap();
        b
    }

    #[test]
    fn group_function_header_is_left_out_for_a_standard_pgn() {
        // A Write Fields for PGN 127508 (not proprietary) has no
        // Manufacturer Code / Industry Code header; writing one shifts
        // every later field by two bytes. Captured as
        // 05 14f201 00 01 01 [01 01] 66 [01 05] (canboat#1002).
        let mut b = write_fields(127508);
        let i = b.add_set_instance(1).unwrap();
        b.push_in_set(1, i, "selectionParameter", Raw(1)).unwrap();
        b.push_in_set(1, i, "selectionValue", Raw(0x66)).unwrap();
        let i = b.add_set_instance(2).unwrap();
        b.push_in_set(2, i, "parameter", Raw(1)).unwrap();
        b.push_in_set(2, i, "value", Raw(5)).unwrap();
        let frame = b.build().unwrap();
        assert_eq!(
            frame.data.as_slice(),
            &[
                0x05, 0x14, 0xf2, 0x01, 0x00, 0x01, 0x01, 0x01, 0x66, 0x01, 0x05
            ]
        );
    }

    #[test]
    fn group_function_header_is_written_for_a_proprietary_pgn() {
        // Furuno's 130845: the header follows the commanded PGN, its
        // Reserved bits all ones -- the bytes the C decodes as
        // Manufacturer Code = Furuno, Industry Code = Marine.
        let mut b = write_fields(130845);
        b.push_by_name("Manufacturer Code", Raw(1855)).unwrap();
        b.push_by_name("Industry Code", Raw(4)).unwrap();
        let frame = b.build().unwrap();
        assert_eq!(
            frame.data.as_slice(),
            &[0x05, 0x1d, 0xff, 0x01, 0x3f, 0x9f, 0x00, 0x00, 0x00]
        );
        let decoded = db().decode(&frame).unwrap();
        assert!(matches!(
            decoded.field_by_name("Manufacturer Code").map(|f| &f.value),
            Some(crate::engine::FieldValue::Lookup { value: 1855, .. })
        ));
    }

    #[test]
    fn group_function_header_must_match_the_commanded_pgn() {
        // Proprietary, but no Manufacturer Code: refused, not sent as
        // "not available".
        let mut b = write_fields(130845);
        b.push_by_name("Industry Code", Raw(4)).unwrap();
        assert_eq!(
            b.build().unwrap_err(),
            EncodeError::ProprietaryHeader {
                field: "Manufacturer Code",
                target_pgn: Some(130845),
                proprietary: true,
            }
        );
        // Standard, but given a header: refused rather than dropped.
        let mut b = write_fields(127508);
        b.push_by_name("Manufacturer Code", Raw(1855)).unwrap();
        assert_eq!(
            b.build().unwrap_err(),
            EncodeError::ProprietaryHeader {
                field: "Manufacturer Code",
                target_pgn: Some(127508),
                proprietary: false,
            }
        );
    }
}