dvb-si 6.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
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
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
//! Satellite Access Table (SAT) — ETSI EN 300 468 §5.2.11.
//!
//! Long-form private section on PID 0x001B with table_id 0x4D. The SAT is a
//! *family*: a common `satellite_access_section()` header carries a 6-bit
//! `satellite_table_id` discriminant ([`SatTableId`]) that selects one of five
//! body structures (position v2, cell fragment, time association, beamhopping
//! time plan, position v3).
//!
//! The body is typed as [`SatBody`] — an enum with one variant per defined
//! layout plus a [`SatBody::Raw`] fallthrough for reserved
//! `satellite_table_id` values 5–63. All five layouts use bit-packed fields; a
//! private bit-level reader/writer handles the extraction and emission.

use crate::error::{Error, Result};
use dvb_common::{Parse, Serialize};

/// table_id for the Satellite Access Table.
pub const TABLE_ID: u8 = 0x4D;
/// Well-known PID on which the SAT is carried (EN 300 468 Table 1, §5.1.3).
pub const PID: u16 = 0x001B;

const HEADER_LEN: usize = 9;
const SECTION_LENGTH_PREFIX: usize = 3;
const CRC_LEN: usize = 4;

fn pad_to_byte(bits: usize) -> usize {
    (8 - (bits % 8)) % 8
}

// ── Bit-level reader/writer ──────────────────────────────────────────────────

struct BitReader<'a> {
    data: &'a [u8],
    bit_pos: usize,
}

impl<'a> BitReader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, bit_pos: 0 }
    }
    fn remaining_bits(&self) -> usize {
        (self.data.len() * 8).saturating_sub(self.bit_pos)
    }
    fn bits_consumed(&self) -> usize {
        self.bit_pos
    }
    fn read_u(&mut self, bits: u8) -> Result<u64> {
        let bits = bits as usize;
        if self.bit_pos + bits > self.data.len() * 8 {
            return Err(Error::BufferTooShort {
                need: self.bit_pos + bits,
                have: self.data.len() * 8,
                what: "SatSection bit reader overrun",
            });
        }
        let mut val: u64 = 0;
        for i in 0..bits {
            let byte_idx = (self.bit_pos + i) / 8;
            let bit_idx = 7 - ((self.bit_pos + i) % 8);
            val = (val << 1) | ((self.data[byte_idx] >> bit_idx) & 1) as u64;
        }
        self.bit_pos += bits;
        Ok(val)
    }
    fn read_i(&mut self, bits: u8) -> Result<i64> {
        let raw = self.read_u(bits)?;
        let bits = bits as usize;
        if raw & (1u64 << (bits - 1)) != 0 {
            Ok((raw as i64) | (!0i64 << bits))
        } else {
            Ok(raw as i64)
        }
    }
    fn skip(&mut self, bits: u8) -> Result<()> {
        if self.bit_pos + bits as usize > self.data.len() * 8 {
            return Err(Error::BufferTooShort {
                need: self.bit_pos + bits as usize,
                have: self.data.len() * 8,
                what: "SatSection bit reader overrun",
            });
        }
        self.bit_pos += bits as usize;
        Ok(())
    }
}

struct BitWriter<'a> {
    buf: &'a mut [u8],
    bit_pos: usize,
}

impl<'a> BitWriter<'a> {
    fn new(buf: &'a mut [u8]) -> Self {
        Self { buf, bit_pos: 0 }
    }
    fn bits_written(&self) -> usize {
        self.bit_pos
    }
    fn write_u(&mut self, bits: u8, val: u64) -> Result<()> {
        let bits = bits as usize;
        if self.bit_pos + bits > self.buf.len() * 8 {
            return Err(Error::BufferTooShort {
                need: self.bit_pos + bits,
                have: self.buf.len() * 8,
                what: "SatSection bit writer overrun",
            });
        }
        for i in 0..bits {
            let byte_idx = (self.bit_pos + i) / 8;
            let bit_idx = 7 - ((self.bit_pos + i) % 8);
            let bit_val = ((val >> (bits - 1 - i)) & 1) as u8;
            self.buf[byte_idx] |= bit_val << bit_idx;
        }
        self.bit_pos += bits;
        Ok(())
    }
    fn write_i(&mut self, bits: u8, val: i64) -> Result<()> {
        self.write_u(bits, val as u64 & ((1u64 << bits) - 1))
    }
    fn write_zero(&mut self, bits: u8) -> Result<()> {
        if self.bit_pos + bits as usize > self.buf.len() * 8 {
            return Err(Error::BufferTooShort {
                need: self.bit_pos + bits as usize,
                have: self.buf.len() * 8,
                what: "SatSection bit writer overrun",
            });
        }
        self.bit_pos += bits as usize;
        Ok(())
    }
}

// ── SatTableId discriminant ─────────────────────────────────────────────────

/// `satellite_table_id` discriminant — selects the SAT body structure
/// (§5.2.11.1, Table 11b).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, num_enum::TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[repr(u8)]
#[non_exhaustive]
pub enum SatTableId {
    /// `satellite_position_v2_info` — TLE/SGP4 orbital elements (§5.2.11.2).
    PositionV2 = 0,
    /// `cell_fragment_info` — earth-surface cell coverage areas (§5.2.11.3).
    CellFragment = 1,
    /// `time_association_info` — NCR↔UTC time association (§5.2.11.4).
    TimeAssociation = 2,
    /// `beamhopping_time_plan_info` — beam illumination schedule (§5.2.11.5).
    BeamhoppingTimePlan = 3,
    /// `satellite_position_v3_info` — ephemeris state vectors (§5.2.11.6).
    PositionV3 = 4,
}

// ── Position V2 (Table 11c) ─────────────────────────────────────────────────

/// Position system selector for PositionV2.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum PositionSystem {
    /// `position_system == 0`: orbital position (BCD 16-bit, west_east_flag).
    Orbital {
        /// `orbital_position` (16 bits, BCD-encoded as 4 digits).
        orbital_position: u16,
        /// `west_east_flag`.
        west_east_flag: bool,
    },
    /// `position_system == 1`: SGP4 TLE elements.
    Sgp4 {
        /// `epoch_year` (8 bits).
        epoch_year: u8,
        /// `day_of_the_year` (16 bits).
        day_of_the_year: u16,
        /// `day_fraction` (32 bits, raw).
        day_fraction: u32,
        /// `mean_motion_first_derivative` (32 bits, raw spfmsbf).
        mean_motion_first_derivative: u32,
        /// `mean_motion_second_derivative` (32 bits, raw spfmsbf).
        mean_motion_second_derivative: u32,
        /// `drag_term` (32 bits, raw spfmsbf).
        drag_term: u32,
        /// `inclination` (32 bits, raw spfmsbf).
        inclination: u32,
        /// `right_ascension_of_the_ascending_node` (32 bits, raw spfmsbf).
        right_ascension: u32,
        /// `eccentricity` (32 bits, raw spfmsbf).
        eccentricity: u32,
        /// `argument_of_perigree` (32 bits, raw spfmsbf).
        argument_of_perigree: u32,
        /// `mean_anomaly` (32 bits, raw spfmsbf).
        mean_anomaly: u32,
        /// `mean_motion` (32 bits, raw spfmsbf).
        mean_motion: u32,
    },
}

/// A satellite entry in the PositionV2 body.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PositionV2Satellite {
    /// `satellite_id` (24 bits).
    pub satellite_id: u32,
    /// Position data (orbital or SGP4).
    pub position: PositionSystem,
}

/// Position V2 body (Table 11c, §5.2.11.2).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PositionV2Body {
    /// Satellite entries.
    pub satellites: Vec<PositionV2Satellite>,
}

// ── Cell Fragment (Table 11d) ────────────────────────────────────────────────

/// Centre coordinates for a cell fragment (present when `first_occurrence == 1`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CellCenter {
    /// `center_latitude` (18 bits, two's complement, `tcimsbf`).
    pub center_latitude: i32,
    /// `center_longitude` (19 bits, two's complement, `tcimsbf`).
    pub center_longitude: i32,
    /// `max_distance` (24 bits).
    pub max_distance: u32,
}

/// A new delivery system entry in a cell fragment.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct NewDeliverySystem {
    /// `new_delivery_system_id` (32 bits).
    pub new_delivery_system_id: u32,
    /// `time_of_application_base` (33 bits).
    pub time_of_application_base: u64,
    /// `time_of_application_ext` (9 bits).
    pub time_of_application_ext: u16,
}

/// An obsolescent delivery system entry in a cell fragment.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ObsolescentDeliverySystem {
    /// `obsolescent_delivery_system_id` (32 bits).
    pub obsolescent_delivery_system_id: u32,
    /// `time_of_obsolescence_base` (33 bits).
    pub time_of_obsolescence_base: u64,
    /// `time_of_obsolescence_ext` (9 bits).
    pub time_of_obsolescence_ext: u16,
}

/// A cell fragment entry (Table 11d, §5.2.11.3).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CellFragment {
    /// `cell_fragment_id` (32 bits).
    pub cell_fragment_id: u32,
    /// `first_occurrence`.
    pub first_occurrence: bool,
    /// `last_occurrence`.
    pub last_occurrence: bool,
    /// Centre coordinates (present iff `first_occurrence`).
    pub center: Option<CellCenter>,
    /// `delivery_system_id` entries (each 32 bits).
    pub delivery_system_ids: Vec<u32>,
    /// New delivery system entries.
    pub new_delivery_systems: Vec<NewDeliverySystem>,
    /// Obsolescent delivery system entries.
    pub obsolescent_delivery_systems: Vec<ObsolescentDeliverySystem>,
}

/// Cell Fragment body (Table 11d, §5.2.11.3).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CellFragmentBody {
    /// Cell fragment entries.
    pub fragments: Vec<CellFragment>,
}

// ── Time Association (Table 11e) ────────────────────────────────────────────

/// Association type coding — ETSI EN 300 468 §5.2.11.4 Table 11f.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum AssociationType {
    /// 0 — UTC without leap second signalling.
    UtcWithoutLeap,
    /// 1 — UTC with leap second signalling.
    UtcWithLeap,
    /// 2..=15 — reserved.
    Reserved(u8),
}

impl AssociationType {
    #[must_use]
    /// Decode from the wire value.  Every value maps (lossless).
    pub fn from_u8(v: u8) -> Self {
        match v & 0x0F {
            0 => Self::UtcWithoutLeap,
            1 => Self::UtcWithLeap,
            v => Self::Reserved(v),
        }
    }

    #[must_use]
    /// Encode to the wire value.  Inverse of `from_u8` / `from_u16`.
    pub fn to_u8(self) -> u8 {
        match self {
            Self::UtcWithoutLeap => 0,
            Self::UtcWithLeap => 1,
            Self::Reserved(v) => v,
        }
    }

    #[must_use]
    /// Human-readable spec display name.
    pub fn name(self) -> &'static str {
        match self {
            Self::UtcWithoutLeap => "UTC without leap second",
            Self::UtcWithLeap => "UTC with leap second",
            Self::Reserved(_) => "Reserved",
        }
    }
}

/// Leap-second signalling info (present when `association_type == 1`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct LeapInfo {
    /// `leap59`.
    pub leap59: bool,
    /// `leap61`.
    pub leap61: bool,
    /// `pastleap59`.
    pub pastleap59: bool,
    /// `pastleap61`.
    pub pastleap61: bool,
}

/// Time Association body (Table 11e, §5.2.11.4).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct TimeAssociationBody {
    /// `association_type` (4 bits, Table 11f).
    pub association_type: AssociationType,
    /// Leap info (present iff `association_type == 1`).
    pub leap_info: Option<LeapInfo>,
    /// `ncr_base` (33 bits).
    pub ncr_base: u64,
    /// `ncr_ext` (9 bits).
    pub ncr_ext: u16,
    /// `association_timestamp_seconds` (64 bits).
    pub association_timestamp_seconds: u64,
    /// `association_timestamp_nanoseconds` (32 bits).
    pub association_timestamp_nanoseconds: u32,
}

// ── Beamhopping Time Plan (Table 11g) ───────────────────────────────────────

/// Mode-specific data in a beamhopping plan entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum BeamhoppingMode {
    /// `time_plan_mode == 0`: simple dwell/on-time.
    Mode0 {
        /// `dwell_duration_base` (33 bits).
        dwell_duration_base: u64,
        /// `dwell_duration_ext` (9 bits).
        dwell_duration_ext: u16,
        /// `on_time_base` (33 bits).
        on_time_base: u64,
        /// `on_time_ext` (9 bits).
        on_time_ext: u16,
    },
    /// `time_plan_mode == 1`: bitmap.
    Mode1 {
        /// `bit_map_size` (15 bits).
        bit_map_size: u16,
        /// `current_slot` (15 bits).
        current_slot: u16,
        /// `slot_transmission_on` flags (bit_map_size entries).
        slot_transmission_on: Vec<bool>,
    },
    /// `time_plan_mode == 2`: grid/revisit/sleep.
    Mode2 {
        /// `grid_size_base` (33 bits).
        grid_size_base: u64,
        /// `grid_size_ext` (9 bits).
        grid_size_ext: u16,
        /// `revisit_duration_base` (33 bits).
        revisit_duration_base: u64,
        /// `revisit_duration_ext` (9 bits).
        revisit_duration_ext: u16,
        /// `sleep_time_base` (33 bits).
        sleep_time_base: u64,
        /// `sleep_time_ext` (9 bits).
        sleep_time_ext: u16,
        /// `sleep_duration_base` (33 bits).
        sleep_duration_base: u64,
        /// `sleep_duration_ext` (9 bits).
        sleep_duration_ext: u16,
    },
    /// Reserved `time_plan_mode` (3): raw body bytes between the common
    /// header and the plan boundary, preserved for byte-exact round-trip.
    Reserved(Vec<u8>),
}

/// A beamhopping plan entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct BeamhoppingPlan {
    /// `beamhopping_time_plan_id` (32 bits).
    pub beamhopping_time_plan_id: u32,
    /// `time_plan_mode` (2 bits).
    pub time_plan_mode: u8,
    /// `time_of_application_base` (33 bits).
    pub time_of_application_base: u64,
    /// `time_of_application_ext` (9 bits).
    pub time_of_application_ext: u16,
    /// `cycle_duration_base` (33 bits).
    pub cycle_duration_base: u64,
    /// `cycle_duration_ext` (9 bits).
    pub cycle_duration_ext: u16,
    /// Mode-specific data.
    pub mode: BeamhoppingMode,
}

/// Beamhopping Time Plan body (Table 11g, §5.2.11.5).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct BeamhoppingTimePlanBody {
    /// Plan entries.
    pub plans: Vec<BeamhoppingPlan>,
}

// ── Position V3 (Table 11h) ─────────────────────────────────────────────────

/// Usable time range (optional, within metadata).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct UsableTime {
    /// `year` (8 bits).
    pub year: u8,
    /// `day` (9 bits).
    pub day: u16,
    /// `day_fraction` (32 bits, spfmsbf raw).
    pub day_fraction: u32,
}

/// Metadata block (optional, within a V3 satellite entry).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PositionV3Metadata {
    /// `total_start_time_year` (8 bits).
    pub total_start_time_year: u8,
    /// `total_start_time_day` (9 bits).
    pub total_start_time_day: u16,
    /// `total_start_time_day_fraction` (32 bits).
    pub total_start_time_day_fraction: u32,
    /// `total_stop_time_year` (8 bits).
    pub total_stop_time_year: u8,
    /// `total_stop_time_day` (9 bits).
    pub total_stop_time_day: u16,
    /// `total_stop_time_day_fraction` (32 bits).
    pub total_stop_time_day_fraction: u32,
    /// `interpolation_flag` — 1 bit.
    pub interpolation_flag: bool,
    /// `interpolation_type` (3 bits, Table 11i).
    pub interpolation_type: InterpolationType,
    /// `interpolation_degree` (3 bits).
    pub interpolation_degree: u8,
    /// Usable start time (optional).
    pub usable_start_time: Option<UsableTime>,
    /// Usable stop time (optional).
    pub usable_stop_time: Option<UsableTime>,
}

/// Interpolation type coding — ETSI EN 300 468 §5.2.11.6 Table 11i.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum InterpolationType {
    /// 0 — Reserved.
    Reserved0,
    /// 1 — Linear.
    Linear,
    /// 2 — Lagrange.
    Lagrange,
    /// 3 — Reserved.
    Reserved3,
    /// 4 — Hermite.
    Hermite,
    /// 5..=7 — Reserved.
    ReservedOther(u8),
}

impl InterpolationType {
    #[must_use]
    /// Decode from the wire value.  Every value maps (lossless).
    pub fn from_u8(v: u8) -> Self {
        match v & 0x07 {
            0 => Self::Reserved0,
            1 => Self::Linear,
            2 => Self::Lagrange,
            3 => Self::Reserved3,
            4 => Self::Hermite,
            v => Self::ReservedOther(v),
        }
    }

    #[must_use]
    /// Encode to the wire value.  Inverse of `from_u8` / `from_u16`.
    pub fn to_u8(self) -> u8 {
        match self {
            Self::Reserved0 => 0,
            Self::Linear => 1,
            Self::Lagrange => 2,
            Self::Reserved3 => 3,
            Self::Hermite => 4,
            Self::ReservedOther(v) => v,
        }
    }

    #[must_use]
    /// Human-readable spec display name.
    pub fn name(self) -> &'static str {
        match self {
            Self::Reserved0 => "Reserved",
            Self::Linear => "Linear",
            Self::Lagrange => "Lagrange",
            Self::Reserved3 => "Reserved",
            Self::Hermite => "Hermite",
            Self::ReservedOther(_) => "Reserved",
        }
    }
}

/// Ephemeris acceleration (optional, 3 × 32-bit spfmsbf).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EphemerisAccel {
    /// `ephemeris_x_ddot` (32 bits, spfmsbf raw).
    pub ephemeris_x_ddot: u32,
    /// `ephemeris_y_ddot` (32 bits, spfmsbf raw).
    pub ephemeris_y_ddot: u32,
    /// `ephemeris_z_ddot` (32 bits, spfmsbf raw).
    pub ephemeris_z_ddot: u32,
}

/// A single ephemeris data point.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EphemerisData {
    /// `epoch_year` (8 bits).
    pub epoch_year: u8,
    /// `epoch_day` (9 bits).
    pub epoch_day: u16,
    /// `epoch_day_fraction` (32 bits).
    pub epoch_day_fraction: u32,
    /// `ephemeris_x` (32 bits, spfmsbf raw).
    pub ephemeris_x: u32,
    /// `ephemeris_y` (32 bits, spfmsbf raw).
    pub ephemeris_y: u32,
    /// `ephemeris_z` (32 bits, spfmsbf raw).
    pub ephemeris_z: u32,
    /// `ephemeris_x_dot` (32 bits, spfmsbf raw).
    pub ephemeris_x_dot: u32,
    /// `ephemeris_y_dot` (32 bits, spfmsbf raw).
    pub ephemeris_y_dot: u32,
    /// `ephemeris_z_dot` (32 bits, spfmsbf raw).
    pub ephemeris_z_dot: u32,
    /// Acceleration (optional).
    pub acceleration: Option<EphemerisAccel>,
}

/// Covariance data (21 × 32-bit elements).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CovarianceData {
    /// `covariance_epoch_year` (8 bits).
    pub covariance_epoch_year: u8,
    /// `covariance_epoch_day` (9 bits).
    pub covariance_epoch_day: u16,
    /// `covariance_epoch_day_fraction` (32 bits).
    pub covariance_epoch_day_fraction: u32,
    /// 21 covariance elements (each 32 bits, spfmsbf raw).
    pub covariance_elements: [u32; 21],
}

/// A satellite entry in the PositionV3 body.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PositionV3Satellite {
    /// `satellite_id` (24 bits).
    pub satellite_id: u32,
    /// `usable_start_time_flag`.
    pub usable_start_time_flag: bool,
    /// `usable_stop_time_flag`.
    pub usable_stop_time_flag: bool,
    /// `ephemeris_accel_flag`.
    pub ephemeris_accel_flag: bool,
    /// `covariance_flag`.
    pub covariance_flag: bool,
    /// Metadata block (optional); its presence also drives the
    /// `metadata_flag` bit on the wire.
    pub metadata: Option<PositionV3Metadata>,
    /// Ephemeris data entries; their count is derived on serialization.
    pub ephemeris_data: Vec<EphemerisData>,
    /// Covariance data (optional).
    pub covariance: Option<CovarianceData>,
}

/// Position V3 body (Table 11h, §5.2.11.6).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PositionV3Body {
    /// `oem_version_major` (4 bits).
    pub oem_version_major: u8,
    /// `oem_version_minor` (4 bits).
    pub oem_version_minor: u8,
    /// `creation_date_year` (8 bits).
    pub creation_date_year: u8,
    /// `creation_date_day` (9 bits).
    pub creation_date_day: u16,
    /// `creation_date_day_fraction` (32 bits).
    pub creation_date_day_fraction: u32,
    /// Satellite entries.
    pub satellites: Vec<PositionV3Satellite>,
}

// ── SatBody enum ────────────────────────────────────────────────────────────

/// The typed body of a SAT section, selected by `satellite_table_id`
/// (Tables 11c–11h).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum SatBody {
    /// `satellite_table_id == 0`: Position V2 (Table 11c).
    PositionV2(PositionV2Body),
    /// `satellite_table_id == 1`: Cell Fragment (Table 11d).
    CellFragment(CellFragmentBody),
    /// `satellite_table_id == 2`: Time Association (Table 11e).
    TimeAssociation(TimeAssociationBody),
    /// `satellite_table_id == 3`: Beamhopping Time Plan (Table 11g).
    BeamhoppingTimePlan(BeamhoppingTimePlanBody),
    /// `satellite_table_id == 4`: Position V3 (Table 11h).
    PositionV3(PositionV3Body),
    /// Reserved `satellite_table_id` (5–63): raw body bytes.
    Raw(Vec<u8>),
}

fn sat_body_serialized_len(body: &SatBody) -> usize {
    match body {
        SatBody::Raw(v) => v.len(),
        _ => {
            // The hardened BitWriter errors (rather than silently truncating)
            // on overrun, so feed it a buffer that's grown until the body fits.
            // Real SAT bodies are bounded by the 12-bit section_length (<4 KiB);
            // an over-large constructed body grows to the cap and is then
            // rejected by the section_length guard in serialize_into — never a
            // panic in this infallible length calc.
            let mut cap = 4096usize;
            loop {
                let mut tmp = vec![0u8; cap];
                let mut writer = BitWriter::new(&mut tmp);
                if sat_body_write(body, &mut writer).is_ok() {
                    break writer.bits_written().div_ceil(8);
                }
                if cap >= 1 << 20 {
                    break cap; // pathological; serialize_into rejects it
                }
                cap *= 2;
            }
        }
    }
}

fn sat_body_write(body: &SatBody, w: &mut BitWriter) -> Result<()> {
    match body {
        SatBody::PositionV2(b) => {
            for sat in &b.satellites {
                w.write_u(24, sat.satellite_id as u64)?;
                w.write_zero(7)?;
                match &sat.position {
                    PositionSystem::Orbital {
                        orbital_position,
                        west_east_flag,
                    } => {
                        w.write_u(1, 0)?;
                        w.write_u(16, *orbital_position as u64)?;
                        w.write_u(1, *west_east_flag as u64)?;
                        w.write_zero(7)?;
                    }
                    PositionSystem::Sgp4 {
                        epoch_year,
                        day_of_the_year,
                        day_fraction,
                        mean_motion_first_derivative,
                        mean_motion_second_derivative,
                        drag_term,
                        inclination,
                        right_ascension,
                        eccentricity,
                        argument_of_perigree,
                        mean_anomaly,
                        mean_motion,
                    } => {
                        w.write_u(1, 1)?;
                        w.write_u(8, *epoch_year as u64)?;
                        w.write_u(16, *day_of_the_year as u64)?;
                        w.write_u(32, *day_fraction as u64)?;
                        w.write_u(32, *mean_motion_first_derivative as u64)?;
                        w.write_u(32, *mean_motion_second_derivative as u64)?;
                        w.write_u(32, *drag_term as u64)?;
                        w.write_u(32, *inclination as u64)?;
                        w.write_u(32, *right_ascension as u64)?;
                        w.write_u(32, *eccentricity as u64)?;
                        w.write_u(32, *argument_of_perigree as u64)?;
                        w.write_u(32, *mean_anomaly as u64)?;
                        w.write_u(32, *mean_motion as u64)?;
                    }
                }
            }
        }
        SatBody::CellFragment(b) => {
            for frag in &b.fragments {
                w.write_u(32, frag.cell_fragment_id as u64)?;
                w.write_u(1, frag.first_occurrence as u64)?;
                w.write_u(1, frag.last_occurrence as u64)?;
                if frag.first_occurrence {
                    if let Some(ref c) = frag.center {
                        w.write_zero(4)?;
                        w.write_i(18, c.center_latitude as i64)?;
                        w.write_zero(5)?;
                        w.write_i(19, c.center_longitude as i64)?;
                        w.write_u(24, c.max_distance as u64)?;
                        w.write_zero(6)?;
                    }
                } else {
                    w.write_zero(4)?;
                }
                w.write_u(10, frag.delivery_system_ids.len() as u64)?;
                for id in &frag.delivery_system_ids {
                    w.write_u(32, *id as u64)?;
                }
                w.write_zero(6)?;
                w.write_u(10, frag.new_delivery_systems.len() as u64)?;
                for nds in &frag.new_delivery_systems {
                    w.write_u(32, nds.new_delivery_system_id as u64)?;
                    w.write_u(33, nds.time_of_application_base)?;
                    w.write_zero(6)?;
                    w.write_u(9, nds.time_of_application_ext as u64)?;
                }
                w.write_zero(6)?;
                w.write_u(10, frag.obsolescent_delivery_systems.len() as u64)?;
                for ods in &frag.obsolescent_delivery_systems {
                    w.write_u(32, ods.obsolescent_delivery_system_id as u64)?;
                    w.write_u(33, ods.time_of_obsolescence_base)?;
                    w.write_zero(6)?;
                    w.write_u(9, ods.time_of_obsolescence_ext as u64)?;
                }
            }
        }
        SatBody::TimeAssociation(b) => {
            w.write_u(4, b.association_type.to_u8() as u64)?;
            if b.association_type.to_u8() == 1 {
                if let Some(ref li) = b.leap_info {
                    w.write_u(1, li.leap59 as u64)?;
                    w.write_u(1, li.leap61 as u64)?;
                    w.write_u(1, li.pastleap59 as u64)?;
                    w.write_u(1, li.pastleap61 as u64)?;
                } else {
                    w.write_zero(4)?;
                }
            } else {
                w.write_zero(4)?;
            }
            w.write_u(33, b.ncr_base)?;
            w.write_zero(6)?;
            w.write_u(9, b.ncr_ext as u64)?;
            w.write_u(64, b.association_timestamp_seconds)?;
            w.write_u(32, b.association_timestamp_nanoseconds as u64)?;
        }
        SatBody::BeamhoppingTimePlan(b) => {
            for plan in &b.plans {
                w.write_u(32, plan.beamhopping_time_plan_id as u64)?;
                w.write_zero(4)?;
                let mode_bits = match &plan.mode {
                    BeamhoppingMode::Mode0 { .. } => 33 + 6 + 9 + 33 + 6 + 9,
                    BeamhoppingMode::Mode1 { bit_map_size, .. } => {
                        let bm = *bit_map_size as usize;
                        let raw = 1 + 15 + 1 + 15 + bm;
                        raw + pad_to_byte(raw)
                    }
                    BeamhoppingMode::Mode2 { .. } => {
                        33 + 6 + 9 + 33 + 6 + 9 + 33 + 6 + 9 + 33 + 6 + 9
                    }
                    BeamhoppingMode::Reserved(v) => v.len() * 8,
                };
                let total_bits_after_length = 8 + 48 + 48 + mode_bits;
                let plan_length_bytes = total_bits_after_length / 8;
                w.write_u(12, plan_length_bytes as u64)?;
                w.write_zero(6)?;
                w.write_u(2, plan.time_plan_mode as u64)?;
                w.write_u(33, plan.time_of_application_base)?;
                w.write_zero(6)?;
                w.write_u(9, plan.time_of_application_ext as u64)?;
                w.write_u(33, plan.cycle_duration_base)?;
                w.write_zero(6)?;
                w.write_u(9, plan.cycle_duration_ext as u64)?;
                match &plan.mode {
                    BeamhoppingMode::Mode0 {
                        dwell_duration_base,
                        dwell_duration_ext,
                        on_time_base,
                        on_time_ext,
                    } => {
                        w.write_u(33, *dwell_duration_base)?;
                        w.write_zero(6)?;
                        w.write_u(9, *dwell_duration_ext as u64)?;
                        w.write_u(33, *on_time_base)?;
                        w.write_zero(6)?;
                        w.write_u(9, *on_time_ext as u64)?;
                    }
                    BeamhoppingMode::Mode1 {
                        bit_map_size,
                        current_slot,
                        slot_transmission_on,
                    } => {
                        w.write_zero(1)?;
                        w.write_u(15, *bit_map_size as u64)?;
                        w.write_zero(1)?;
                        w.write_u(15, *current_slot as u64)?;
                        for &on in slot_transmission_on {
                            w.write_u(1, on as u64)?;
                        }
                        let total = 1 + 15 + 1 + 15 + *bit_map_size as usize;
                        for _ in 0..pad_to_byte(total) {
                            w.write_zero(1)?;
                        }
                    }
                    BeamhoppingMode::Mode2 {
                        grid_size_base,
                        grid_size_ext,
                        revisit_duration_base,
                        revisit_duration_ext,
                        sleep_time_base,
                        sleep_time_ext,
                        sleep_duration_base,
                        sleep_duration_ext,
                    } => {
                        w.write_u(33, *grid_size_base)?;
                        w.write_zero(6)?;
                        w.write_u(9, *grid_size_ext as u64)?;
                        w.write_u(33, *revisit_duration_base)?;
                        w.write_zero(6)?;
                        w.write_u(9, *revisit_duration_ext as u64)?;
                        w.write_u(33, *sleep_time_base)?;
                        w.write_zero(6)?;
                        w.write_u(9, *sleep_time_ext as u64)?;
                        w.write_u(33, *sleep_duration_base)?;
                        w.write_zero(6)?;
                        w.write_u(9, *sleep_duration_ext as u64)?;
                    }
                    BeamhoppingMode::Reserved(v) => {
                        for &b in v {
                            w.write_u(8, b as u64)?;
                        }
                    }
                }
            }
        }
        SatBody::PositionV3(b) => {
            w.write_u(4, b.oem_version_major as u64)?;
            w.write_u(4, b.oem_version_minor as u64)?;
            w.write_u(8, b.creation_date_year as u64)?;
            w.write_zero(7)?;
            w.write_u(9, b.creation_date_day as u64)?;
            w.write_u(32, b.creation_date_day_fraction as u64)?;
            for sat in &b.satellites {
                w.write_u(24, sat.satellite_id as u64)?;
                w.write_zero(3)?;
                w.write_u(1, u8::from(sat.metadata.is_some()) as u64)?;
                w.write_u(1, sat.usable_start_time_flag as u64)?;
                w.write_u(1, sat.usable_stop_time_flag as u64)?;
                w.write_u(1, sat.ephemeris_accel_flag as u64)?;
                w.write_u(1, sat.covariance_flag as u64)?;
                if let Some(ref md) = sat.metadata {
                    w.write_u(8, md.total_start_time_year as u64)?;
                    w.write_zero(7)?;
                    w.write_u(9, md.total_start_time_day as u64)?;
                    w.write_u(32, md.total_start_time_day_fraction as u64)?;
                    w.write_u(8, md.total_stop_time_year as u64)?;
                    w.write_zero(7)?;
                    w.write_u(9, md.total_stop_time_day as u64)?;
                    w.write_u(32, md.total_stop_time_day_fraction as u64)?;
                    w.write_zero(1)?;
                    w.write_u(1, md.interpolation_flag as u64)?;
                    w.write_u(3, md.interpolation_type.to_u8() as u64)?;
                    w.write_u(3, md.interpolation_degree as u64)?;
                    if sat.usable_start_time_flag {
                        if let Some(ref ut) = md.usable_start_time {
                            w.write_u(8, ut.year as u64)?;
                            w.write_zero(7)?;
                            w.write_u(9, ut.day as u64)?;
                            w.write_u(32, ut.day_fraction as u64)?;
                        } else {
                            w.write_zero(8)?;
                            w.write_zero(7)?;
                            w.write_zero(9)?;
                            w.write_zero(32)?;
                        }
                    }
                    if sat.usable_stop_time_flag {
                        if let Some(ref ut) = md.usable_stop_time {
                            w.write_u(8, ut.year as u64)?;
                            w.write_zero(7)?;
                            w.write_u(9, ut.day as u64)?;
                            w.write_u(32, ut.day_fraction as u64)?;
                        } else {
                            w.write_zero(8)?;
                            w.write_zero(7)?;
                            w.write_zero(9)?;
                            w.write_zero(32)?;
                        }
                    }
                }
                w.write_u(16, sat.ephemeris_data.len() as u64)?;
                for ed in &sat.ephemeris_data {
                    w.write_u(8, ed.epoch_year as u64)?;
                    w.write_zero(7)?;
                    w.write_u(9, ed.epoch_day as u64)?;
                    w.write_u(32, ed.epoch_day_fraction as u64)?;
                    w.write_u(32, ed.ephemeris_x as u64)?;
                    w.write_u(32, ed.ephemeris_y as u64)?;
                    w.write_u(32, ed.ephemeris_z as u64)?;
                    w.write_u(32, ed.ephemeris_x_dot as u64)?;
                    w.write_u(32, ed.ephemeris_y_dot as u64)?;
                    w.write_u(32, ed.ephemeris_z_dot as u64)?;
                    if sat.ephemeris_accel_flag {
                        if let Some(ref acc) = ed.acceleration {
                            w.write_u(32, acc.ephemeris_x_ddot as u64)?;
                            w.write_u(32, acc.ephemeris_y_ddot as u64)?;
                            w.write_u(32, acc.ephemeris_z_ddot as u64)?;
                        } else {
                            w.write_zero(32)?;
                            w.write_zero(32)?;
                            w.write_zero(32)?;
                        }
                    }
                }
                if sat.covariance_flag {
                    if let Some(ref cov) = sat.covariance {
                        w.write_u(8, cov.covariance_epoch_year as u64)?;
                        w.write_zero(7)?;
                        w.write_u(9, cov.covariance_epoch_day as u64)?;
                        w.write_u(32, cov.covariance_epoch_day_fraction as u64)?;
                        for elem in &cov.covariance_elements {
                            w.write_u(32, *elem as u64)?;
                        }
                    } else {
                        w.write_zero(8)?;
                        w.write_zero(7)?;
                        w.write_zero(9)?;
                        w.write_zero(32)?;
                        for _ in 0..21 {
                            w.write_zero(32)?;
                        }
                    }
                }
            }
        }
        SatBody::Raw(_) => {}
    }
    Ok(())
}

fn sat_body_parse(sat_table_id: u8, data: &[u8]) -> Result<SatBody> {
    if data.is_empty() && sat_table_id <= 4 {
        return Ok(match sat_table_id {
            0 => SatBody::PositionV2(PositionV2Body {
                satellites: Vec::new(),
            }),
            1 => SatBody::CellFragment(CellFragmentBody {
                fragments: Vec::new(),
            }),
            3 => SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody { plans: Vec::new() }),
            _ => {
                return Err(Error::BufferTooShort {
                    need: 1,
                    have: 0,
                    what: "SatSection body (non-loop type requires data)",
                });
            }
        });
    }
    let mut r = BitReader::new(data);
    match sat_table_id {
        0 => {
            let mut satellites = Vec::new();
            while r.remaining_bits() > 24 + 7 {
                let satellite_id = r.read_u(24)? as u32;
                r.skip(7)?;
                let position_system = r.read_u(1)?;
                let position = if position_system == 0 {
                    const ORBITAL_BITS: usize = 16 + 1 + 7;
                    if r.remaining_bits() < ORBITAL_BITS {
                        return Err(Error::BufferTooShort {
                            need: ORBITAL_BITS,
                            have: r.remaining_bits(),
                            what: "SatSection PositionV2 Orbital fields",
                        });
                    }
                    let orbital_position = r.read_u(16)? as u16;
                    let west_east_flag = r.read_u(1)? != 0;
                    r.skip(7)?;
                    PositionSystem::Orbital {
                        orbital_position,
                        west_east_flag,
                    }
                } else {
                    const SGP4_BITS: usize = 8 + 16 + 32 * 10;
                    if r.remaining_bits() < SGP4_BITS {
                        return Err(Error::BufferTooShort {
                            need: SGP4_BITS,
                            have: r.remaining_bits(),
                            what: "SatSection PositionV2 SGP4 fields",
                        });
                    }
                    let epoch_year = r.read_u(8)? as u8;
                    let day_of_the_year = r.read_u(16)? as u16;
                    let day_fraction = r.read_u(32)? as u32;
                    let mean_motion_first_derivative = r.read_u(32)? as u32;
                    let mean_motion_second_derivative = r.read_u(32)? as u32;
                    let drag_term = r.read_u(32)? as u32;
                    let inclination = r.read_u(32)? as u32;
                    let right_ascension = r.read_u(32)? as u32;
                    let eccentricity = r.read_u(32)? as u32;
                    let argument_of_perigree = r.read_u(32)? as u32;
                    let mean_anomaly = r.read_u(32)? as u32;
                    let mean_motion = r.read_u(32)? as u32;
                    PositionSystem::Sgp4 {
                        epoch_year,
                        day_of_the_year,
                        day_fraction,
                        mean_motion_first_derivative,
                        mean_motion_second_derivative,
                        drag_term,
                        inclination,
                        right_ascension,
                        eccentricity,
                        argument_of_perigree,
                        mean_anomaly,
                        mean_motion,
                    }
                };
                satellites.push(PositionV2Satellite {
                    satellite_id,
                    position,
                });
            }
            Ok(SatBody::PositionV2(PositionV2Body { satellites }))
        }
        1 => {
            let mut fragments = Vec::new();
            while r.remaining_bits() >= 32 + 2 {
                let cell_fragment_id = r.read_u(32)? as u32;
                let first_occurrence = r.read_u(1)? != 0;
                let last_occurrence = r.read_u(1)? != 0;
                let center = if first_occurrence {
                    const CENTER_BITS: usize = 4 + 18 + 5 + 19 + 24 + 6;
                    if r.remaining_bits() < CENTER_BITS {
                        return Err(Error::BufferTooShort {
                            need: CENTER_BITS,
                            have: r.remaining_bits(),
                            what: "SatSection CellFragment center",
                        });
                    }
                    r.skip(4)?;
                    let center_latitude = r.read_i(18)? as i32;
                    r.skip(5)?;
                    let center_longitude = r.read_i(19)? as i32;
                    let max_distance = r.read_u(24)? as u32;
                    r.skip(6)?;
                    Some(CellCenter {
                        center_latitude,
                        center_longitude,
                        max_distance,
                    })
                } else {
                    r.skip(4)?;
                    None
                };
                let dsid_count = r.read_u(10)? as usize;
                if r.remaining_bits() < dsid_count * 32 {
                    return Err(Error::BufferTooShort {
                        need: dsid_count * 32,
                        have: r.remaining_bits(),
                        what: "SatSection CellFragment delivery_system_ids",
                    });
                }
                let mut delivery_system_ids =
                    Vec::with_capacity(dsid_count.min(r.remaining_bits() / 32));
                for _ in 0..dsid_count {
                    delivery_system_ids.push(r.read_u(32)? as u32);
                }
                r.skip(6)?;
                let nds_count = r.read_u(10)? as usize;
                const NDS_ENTRY_BITS: usize = 32 + 33 + 6 + 9;
                if r.remaining_bits() < nds_count * NDS_ENTRY_BITS {
                    return Err(Error::BufferTooShort {
                        need: nds_count * NDS_ENTRY_BITS,
                        have: r.remaining_bits(),
                        what: "SatSection CellFragment new_delivery_systems",
                    });
                }
                let mut new_delivery_systems =
                    Vec::with_capacity(nds_count.min(r.remaining_bits() / NDS_ENTRY_BITS));
                for _ in 0..nds_count {
                    let new_delivery_system_id = r.read_u(32)? as u32;
                    let time_of_application_base = r.read_u(33)?;
                    r.skip(6)?;
                    let time_of_application_ext = r.read_u(9)? as u16;
                    new_delivery_systems.push(NewDeliverySystem {
                        new_delivery_system_id,
                        time_of_application_base,
                        time_of_application_ext,
                    });
                }
                r.skip(6)?;
                let ods_count = r.read_u(10)? as usize;
                if r.remaining_bits() < ods_count * NDS_ENTRY_BITS {
                    return Err(Error::BufferTooShort {
                        need: ods_count * NDS_ENTRY_BITS,
                        have: r.remaining_bits(),
                        what: "SatSection CellFragment obsolescent_delivery_systems",
                    });
                }
                let mut obsolescent_delivery_systems =
                    Vec::with_capacity(ods_count.min(r.remaining_bits() / NDS_ENTRY_BITS));
                for _ in 0..ods_count {
                    let obsolescent_delivery_system_id = r.read_u(32)? as u32;
                    let time_of_obsolescence_base = r.read_u(33)?;
                    r.skip(6)?;
                    let time_of_obsolescence_ext = r.read_u(9)? as u16;
                    obsolescent_delivery_systems.push(ObsolescentDeliverySystem {
                        obsolescent_delivery_system_id,
                        time_of_obsolescence_base,
                        time_of_obsolescence_ext,
                    });
                }
                fragments.push(CellFragment {
                    cell_fragment_id,
                    first_occurrence,
                    last_occurrence,
                    center,
                    delivery_system_ids,
                    new_delivery_systems,
                    obsolescent_delivery_systems,
                });
            }
            Ok(SatBody::CellFragment(CellFragmentBody { fragments }))
        }
        2 => {
            const TIME_ASSOC_MIN_BITS: usize = 4 + 4 + 33 + 6 + 9 + 64 + 32;
            if r.remaining_bits() < TIME_ASSOC_MIN_BITS {
                return Err(Error::BufferTooShort {
                    need: TIME_ASSOC_MIN_BITS,
                    have: r.remaining_bits(),
                    what: "SatSection TimeAssociation body",
                });
            }
            let association_type = AssociationType::from_u8(r.read_u(4)? as u8);
            let leap_info = if association_type.to_u8() == 1 {
                Some(LeapInfo {
                    leap59: r.read_u(1)? != 0,
                    leap61: r.read_u(1)? != 0,
                    pastleap59: r.read_u(1)? != 0,
                    pastleap61: r.read_u(1)? != 0,
                })
            } else {
                r.skip(4)?;
                None
            };
            let ncr_base = r.read_u(33)?;
            r.skip(6)?;
            let ncr_ext = r.read_u(9)? as u16;
            let association_timestamp_seconds = r.read_u(64)?;
            let association_timestamp_nanoseconds = r.read_u(32)? as u32;
            Ok(SatBody::TimeAssociation(TimeAssociationBody {
                association_type,
                leap_info,
                ncr_base,
                ncr_ext,
                association_timestamp_seconds,
                association_timestamp_nanoseconds,
            }))
        }
        3 => {
            let mut plans = Vec::new();
            while r.remaining_bits() >= 32 + 4 + 12 {
                let beamhopping_time_plan_id = r.read_u(32)? as u32;
                r.skip(4)?;
                let plan_length = r.read_u(12)? as usize;
                let plan_end_bits = r.bits_consumed() + plan_length * 8;
                r.skip(6)?;
                let time_plan_mode = r.read_u(2)? as u8;
                let time_of_application_base = r.read_u(33)?;
                r.skip(6)?;
                let time_of_application_ext = r.read_u(9)? as u16;
                let cycle_duration_base = r.read_u(33)?;
                r.skip(6)?;
                let cycle_duration_ext = r.read_u(9)? as u16;
                let mode = match time_plan_mode {
                    0 => {
                        const MODE0_BITS: usize = 33 + 6 + 9 + 33 + 6 + 9;
                        if r.remaining_bits() < MODE0_BITS {
                            return Err(Error::BufferTooShort {
                                need: MODE0_BITS,
                                have: r.remaining_bits(),
                                what: "SatSection Beamhopping Mode0",
                            });
                        }
                        let dwell_duration_base = r.read_u(33)?;
                        r.skip(6)?;
                        let dwell_duration_ext = r.read_u(9)? as u16;
                        let on_time_base = r.read_u(33)?;
                        r.skip(6)?;
                        let on_time_ext = r.read_u(9)? as u16;
                        BeamhoppingMode::Mode0 {
                            dwell_duration_base,
                            dwell_duration_ext,
                            on_time_base,
                            on_time_ext,
                        }
                    }
                    1 => {
                        const MODE1_HEADER_BITS: usize = 1 + 15 + 1 + 15;
                        if r.remaining_bits() < MODE1_HEADER_BITS {
                            return Err(Error::BufferTooShort {
                                need: MODE1_HEADER_BITS,
                                have: r.remaining_bits(),
                                what: "SatSection Beamhopping Mode1 header",
                            });
                        }
                        r.skip(1)?;
                        let bit_map_size = r.read_u(15)? as u16;
                        r.skip(1)?;
                        let current_slot = r.read_u(15)? as u16;
                        if r.remaining_bits() < bit_map_size as usize {
                            return Err(Error::BufferTooShort {
                                need: bit_map_size as usize,
                                have: r.remaining_bits(),
                                what: "SatSection Beamhopping Mode1 bitmap",
                            });
                        }
                        let mut slot_transmission_on =
                            Vec::with_capacity((bit_map_size as usize).min(r.remaining_bits()));
                        for _ in 0..bit_map_size {
                            slot_transmission_on.push(r.read_u(1)? != 0);
                        }
                        let total = 1 + 15 + 1 + 15 + bit_map_size as usize;
                        r.skip(pad_to_byte(total) as u8)?;
                        BeamhoppingMode::Mode1 {
                            bit_map_size,
                            current_slot,
                            slot_transmission_on,
                        }
                    }
                    2 => {
                        const MODE2_BITS: usize = 33 + 6 + 9 + 33 + 6 + 9 + 33 + 6 + 9 + 33 + 6 + 9;
                        if r.remaining_bits() < MODE2_BITS {
                            return Err(Error::BufferTooShort {
                                need: MODE2_BITS,
                                have: r.remaining_bits(),
                                what: "SatSection Beamhopping Mode2",
                            });
                        }
                        let grid_size_base = r.read_u(33)?;
                        r.skip(6)?;
                        let grid_size_ext = r.read_u(9)? as u16;
                        let revisit_duration_base = r.read_u(33)?;
                        r.skip(6)?;
                        let revisit_duration_ext = r.read_u(9)? as u16;
                        let sleep_time_base = r.read_u(33)?;
                        r.skip(6)?;
                        let sleep_time_ext = r.read_u(9)? as u16;
                        let sleep_duration_base = r.read_u(33)?;
                        r.skip(6)?;
                        let sleep_duration_ext = r.read_u(9)? as u16;
                        BeamhoppingMode::Mode2 {
                            grid_size_base,
                            grid_size_ext,
                            revisit_duration_base,
                            revisit_duration_ext,
                            sleep_time_base,
                            sleep_time_ext,
                            sleep_duration_base,
                            sleep_duration_ext,
                        }
                    }
                    _ => {
                        let start_byte = r.bits_consumed().div_ceil(8);
                        let end_byte = plan_end_bits / 8;
                        let raw = if start_byte < end_byte && end_byte <= data.len() {
                            data[start_byte..end_byte].to_vec()
                        } else {
                            Vec::new()
                        };
                        BeamhoppingMode::Reserved(raw)
                    }
                };
                r.bit_pos = plan_end_bits;
                plans.push(BeamhoppingPlan {
                    beamhopping_time_plan_id,
                    time_plan_mode,
                    time_of_application_base,
                    time_of_application_ext,
                    cycle_duration_base,
                    cycle_duration_ext,
                    mode,
                });
            }
            Ok(SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
                plans,
            }))
        }
        4 => {
            const POS_V3_HEADER_BITS: usize = 4 + 4 + 8 + 7 + 9 + 32;
            if r.remaining_bits() < POS_V3_HEADER_BITS {
                return Err(Error::BufferTooShort {
                    need: POS_V3_HEADER_BITS,
                    have: r.remaining_bits(),
                    what: "SatSection PositionV3 body header",
                });
            }
            let oem_version_major = r.read_u(4)? as u8;
            let oem_version_minor = r.read_u(4)? as u8;
            let creation_date_year = r.read_u(8)? as u8;
            r.skip(7)?;
            let creation_date_day = r.read_u(9)? as u16;
            let creation_date_day_fraction = r.read_u(32)? as u32;
            let mut satellites = Vec::new();
            while r.remaining_bits() >= 24 + 3 + 5 {
                let satellite_id = r.read_u(24)? as u32;
                r.skip(3)?;
                let metadata_flag = r.read_u(1)? != 0;
                let usable_start_time_flag = r.read_u(1)? != 0;
                let usable_stop_time_flag = r.read_u(1)? != 0;
                let ephemeris_accel_flag = r.read_u(1)? != 0;
                let covariance_flag = r.read_u(1)? != 0;
                let metadata = if metadata_flag {
                    const METADATA_FIXED_BITS: usize =
                        8 + 7 + 9 + 32 + 8 + 7 + 9 + 32 + 1 + 1 + 3 + 3;
                    if r.remaining_bits() < METADATA_FIXED_BITS {
                        return Err(Error::BufferTooShort {
                            need: METADATA_FIXED_BITS,
                            have: r.remaining_bits(),
                            what: "SatSection PositionV3 metadata",
                        });
                    }
                    let total_start_time_year = r.read_u(8)? as u8;
                    r.skip(7)?;
                    let total_start_time_day = r.read_u(9)? as u16;
                    let total_start_time_day_fraction = r.read_u(32)? as u32;
                    let total_stop_time_year = r.read_u(8)? as u8;
                    r.skip(7)?;
                    let total_stop_time_day = r.read_u(9)? as u16;
                    let total_stop_time_day_fraction = r.read_u(32)? as u32;
                    r.skip(1)?;
                    let interpolation_flag = r.read_u(1)? != 0;
                    let interpolation_type = InterpolationType::from_u8(r.read_u(3)? as u8);
                    let interpolation_degree = r.read_u(3)? as u8;
                    let usable_start_time = if usable_start_time_flag {
                        const USABLE_TIME_BITS: usize = 8 + 7 + 9 + 32;
                        if r.remaining_bits() < USABLE_TIME_BITS {
                            return Err(Error::BufferTooShort {
                                need: USABLE_TIME_BITS,
                                have: r.remaining_bits(),
                                what: "SatSection PositionV3 usable_start_time",
                            });
                        }
                        let year = r.read_u(8)? as u8;
                        r.skip(7)?;
                        let day = r.read_u(9)? as u16;
                        let day_fraction = r.read_u(32)? as u32;
                        Some(UsableTime {
                            year,
                            day,
                            day_fraction,
                        })
                    } else {
                        None
                    };
                    let usable_stop_time = if usable_stop_time_flag {
                        const USABLE_TIME_BITS: usize = 8 + 7 + 9 + 32;
                        if r.remaining_bits() < USABLE_TIME_BITS {
                            return Err(Error::BufferTooShort {
                                need: USABLE_TIME_BITS,
                                have: r.remaining_bits(),
                                what: "SatSection PositionV3 usable_stop_time",
                            });
                        }
                        let year = r.read_u(8)? as u8;
                        r.skip(7)?;
                        let day = r.read_u(9)? as u16;
                        let day_fraction = r.read_u(32)? as u32;
                        Some(UsableTime {
                            year,
                            day,
                            day_fraction,
                        })
                    } else {
                        None
                    };
                    Some(PositionV3Metadata {
                        total_start_time_year,
                        total_start_time_day,
                        total_start_time_day_fraction,
                        total_stop_time_year,
                        total_stop_time_day,
                        total_stop_time_day_fraction,
                        interpolation_flag,
                        interpolation_type,
                        interpolation_degree,
                        usable_start_time,
                        usable_stop_time,
                    })
                } else {
                    None
                };
                let ephemeris_data_count = r.read_u(16)? as u16;
                let entry_bits: usize =
                    8 + 7 + 9 + 32 + 32 * 6 + if ephemeris_accel_flag { 32 * 3 } else { 0 };
                let mut ephemeris_data = Vec::with_capacity(
                    (ephemeris_data_count as usize)
                        .min(r.remaining_bits().saturating_sub(entry_bits) / entry_bits + 1),
                );
                for _ in 0..ephemeris_data_count {
                    if r.remaining_bits() < entry_bits {
                        return Err(Error::BufferTooShort {
                            need: entry_bits,
                            have: r.remaining_bits(),
                            what: "SatSection PositionV3 ephemeris_data entry",
                        });
                    }
                    let epoch_year = r.read_u(8)? as u8;
                    r.skip(7)?;
                    let epoch_day = r.read_u(9)? as u16;
                    let epoch_day_fraction = r.read_u(32)? as u32;
                    let ephemeris_x = r.read_u(32)? as u32;
                    let ephemeris_y = r.read_u(32)? as u32;
                    let ephemeris_z = r.read_u(32)? as u32;
                    let ephemeris_x_dot = r.read_u(32)? as u32;
                    let ephemeris_y_dot = r.read_u(32)? as u32;
                    let ephemeris_z_dot = r.read_u(32)? as u32;
                    let acceleration = if ephemeris_accel_flag {
                        Some(EphemerisAccel {
                            ephemeris_x_ddot: r.read_u(32)? as u32,
                            ephemeris_y_ddot: r.read_u(32)? as u32,
                            ephemeris_z_ddot: r.read_u(32)? as u32,
                        })
                    } else {
                        None
                    };
                    ephemeris_data.push(EphemerisData {
                        epoch_year,
                        epoch_day,
                        epoch_day_fraction,
                        ephemeris_x,
                        ephemeris_y,
                        ephemeris_z,
                        ephemeris_x_dot,
                        ephemeris_y_dot,
                        ephemeris_z_dot,
                        acceleration,
                    });
                }
                let covariance = if covariance_flag {
                    const COV_HEADER_BITS: usize = 8 + 7 + 9 + 32;
                    const COV_ELEMENTS_BITS: usize = 21 * 32;
                    const COV_BITS: usize = COV_HEADER_BITS + COV_ELEMENTS_BITS;
                    if r.remaining_bits() < COV_BITS {
                        return Err(Error::BufferTooShort {
                            need: COV_BITS,
                            have: r.remaining_bits(),
                            what: "SatSection PositionV3 covariance",
                        });
                    }
                    let covariance_epoch_year = r.read_u(8)? as u8;
                    r.skip(7)?;
                    let covariance_epoch_day = r.read_u(9)? as u16;
                    let covariance_epoch_day_fraction = r.read_u(32)? as u32;
                    let mut covariance_elements = [0u32; 21];
                    for elem in &mut covariance_elements {
                        *elem = r.read_u(32)? as u32;
                    }
                    Some(CovarianceData {
                        covariance_epoch_year,
                        covariance_epoch_day,
                        covariance_epoch_day_fraction,
                        covariance_elements,
                    })
                } else {
                    None
                };
                satellites.push(PositionV3Satellite {
                    satellite_id,
                    usable_start_time_flag,
                    usable_stop_time_flag,
                    ephemeris_accel_flag,
                    covariance_flag,
                    metadata,
                    ephemeris_data,
                    covariance,
                });
            }
            Ok(SatBody::PositionV3(PositionV3Body {
                oem_version_major,
                oem_version_minor,
                creation_date_year,
                creation_date_day,
                creation_date_day_fraction,
                satellites,
            }))
        }
        _ => Ok(SatBody::Raw(data.to_vec())),
    }
}

// ── SatSection ──────────────────────────────────────────────────────────────

/// Satellite Access Table section (EN 300 468 §5.2.11.1, Table 11a).
///
/// The body is typed as [`SatBody`], selected by `satellite_table_id`.
/// All body fields are owned numeric values; the section does not borrow
/// from the input buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SatSection {
    /// 6-bit discriminant selecting the body structure (see [`SatTableId`]).
    pub satellite_table_id: u8,
    /// `private_indicator` — byte 1 bit 6 (Table 11a).
    pub private_indicator: bool,
    /// 10-bit sub_table discriminator.
    pub table_count: u16,
    /// 5-bit sub_table version number.
    pub version_number: u8,
    /// When `true`, this sub_table is currently applicable.
    pub current_next_indicator: bool,
    /// Section number within the sub_table.
    pub section_number: u8,
    /// Highest section number of the sub_table.
    pub last_section_number: u8,
    /// Typed body — interpret per `satellite_table_id`.
    pub body: SatBody,
}

impl SatSection {
    /// Typed view of `satellite_table_id`, or `None` if reserved (5–63).
    #[must_use]
    pub fn kind(&self) -> Option<SatTableId> {
        SatTableId::try_from(self.satellite_table_id).ok()
    }
}

impl<'a> Parse<'a> for SatSection {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let min_len = HEADER_LEN + CRC_LEN;
        if bytes.len() < min_len {
            return Err(Error::BufferTooShort {
                need: min_len,
                have: bytes.len(),
                what: "SatSection",
            });
        }
        if bytes[0] != TABLE_ID {
            return Err(Error::UnexpectedTableId {
                table_id: bytes[0],
                what: "SatSection",
                expected: &[TABLE_ID],
            });
        }
        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
        let total = super::check_section_length(
            bytes.len(),
            SECTION_LENGTH_PREFIX,
            section_length,
            HEADER_LEN + CRC_LEN,
        )?;
        let satellite_table_id = bytes[3] >> 2;
        let private_indicator = (bytes[1] & 0x40) != 0;
        let table_count = (((bytes[3] & 0x03) as u16) << 8) | bytes[4] as u16;
        let version_number = (bytes[5] >> 1) & 0x1F;
        let current_next_indicator = bytes[5] & 0x01 != 0;
        let section_number = bytes[6];
        let last_section_number = bytes[7];
        let body_data = &bytes[HEADER_LEN..total - CRC_LEN];
        let body = sat_body_parse(satellite_table_id, body_data)?;
        Ok(SatSection {
            satellite_table_id,
            private_indicator,
            table_count,
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            body,
        })
    }
}

impl Serialize for SatSection {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        HEADER_LEN + sat_body_serialized_len(&self.body) + CRC_LEN
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        let section_length_usize = len - SECTION_LENGTH_PREFIX;
        if section_length_usize > 0x0FFF {
            return Err(Error::SectionLengthOverflow {
                declared: section_length_usize,
                available: 0x0FFF,
            });
        }
        let section_length = section_length_usize as u16;
        if let SatBody::PositionV3(ref v3) = self.body {
            for sat in &v3.satellites {
                if sat.ephemeris_data.len() > u16::MAX as usize {
                    return Err(Error::SectionLengthOverflow {
                        declared: sat.ephemeris_data.len(),
                        available: u16::MAX as usize,
                    });
                }
            }
        }
        buf[0] = TABLE_ID;
        buf[1] = super::SECTION_B1_SSI
            | (u8::from(self.private_indicator) << 6)
            | super::SECTION_B1_RESERVED_HI
            | ((section_length >> 8) as u8 & 0x0F);
        buf[2] = (section_length & 0xFF) as u8;
        buf[3] = (self.satellite_table_id << 2) | ((self.table_count >> 8) as u8 & 0x03);
        buf[4] = (self.table_count & 0xFF) as u8;
        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
        buf[6] = self.section_number;
        buf[7] = self.last_section_number;
        buf[8] = 0x00;
        let body_start = HEADER_LEN;
        match &self.body {
            SatBody::Raw(v) => {
                buf[body_start..body_start + v.len()].copy_from_slice(v);
            }
            _ => {
                let body_byte_len = sat_body_serialized_len(&self.body);
                for b in &mut buf[body_start..body_start + body_byte_len] {
                    *b = 0;
                }
                let mut writer = BitWriter::new(&mut buf[body_start..body_start + body_byte_len]);
                sat_body_write(&self.body, &mut writer)?;
            }
        }
        let body_end = HEADER_LEN + sat_body_serialized_len(&self.body);
        let crc = dvb_common::crc32_mpeg2::compute(&buf[..body_end]);
        buf[body_end..len].copy_from_slice(&crc.to_be_bytes());
        Ok(len)
    }
}
impl<'a> crate::traits::TableDef<'a> for SatSection {
    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
    const NAME: &'static str = "SATELLITE_ACCESS";
}

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

    fn build_sat(stid: u8, table_count: u16, body: &SatBody) -> Vec<u8> {
        let sat = SatSection {
            satellite_table_id: stid,
            private_indicator: true,
            table_count,
            version_number: 5,
            current_next_indicator: true,
            section_number: 0,
            last_section_number: 0,
            body: body.clone(),
        };
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        buf
    }

    fn build_sat_private_indicator_false(stid: u8, body: &SatBody) -> Vec<u8> {
        let sat = SatSection {
            satellite_table_id: stid,
            private_indicator: false,
            table_count: 0,
            version_number: 5,
            current_next_indicator: true,
            section_number: 0,
            last_section_number: 0,
            body: body.clone(),
        };
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        buf
    }

    #[test]
    fn parse_raw_body() {
        let body_data = [0xAA, 0xBB, 0xCC, 0xDD];
        let bytes = build_sat(7, 0, &SatBody::Raw(body_data.to_vec()));
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 7);
        assert_eq!(sat.kind(), None);
        assert_eq!(sat.body, SatBody::Raw(body_data.to_vec()));
    }

    #[test]
    fn private_indicator_false_round_trip() {
        let body = SatBody::TimeAssociation(TimeAssociationBody {
            association_type: AssociationType::UtcWithoutLeap,
            leap_info: None,
            ncr_base: 0,
            ncr_ext: 0,
            association_timestamp_seconds: 0,
            association_timestamp_nanoseconds: 0,
        });
        let bytes = build_sat_private_indicator_false(2, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        assert!(!sat.private_indicator);
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(
            bytes, buf2,
            "byte-exact round-trip with private_indicator=false"
        );
    }

    #[test]
    fn parse_position_v3_discriminant() {
        let body = SatBody::PositionV3(PositionV3Body {
            oem_version_major: 1,
            oem_version_minor: 0,
            creation_date_year: 25,
            creation_date_day: 100,
            creation_date_day_fraction: 0,
            satellites: Vec::new(),
        });
        let bytes = build_sat(4, 0x1A3, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 4);
        assert_eq!(sat.kind(), Some(SatTableId::PositionV3));
        assert_eq!(sat.table_count, 0x1A3);
    }

    #[test]
    fn time_association_round_trip() {
        let body = SatBody::TimeAssociation(TimeAssociationBody {
            association_type: AssociationType::UtcWithLeap,
            leap_info: Some(LeapInfo {
                leap59: true,
                leap61: false,
                pastleap59: false,
                pastleap61: true,
            }),
            ncr_base: 0x0000_AAAA_AAAA_u64,
            ncr_ext: 0x1AA,
            association_timestamp_seconds: 0x12345678_9ABCDEF0,
            association_timestamp_nanoseconds: 0xDEADBEEF,
        });
        let bytes = build_sat(2, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::TimeAssociation(ta) => {
                assert_eq!(ta.association_type, AssociationType::UtcWithLeap);
                let li = ta.leap_info.as_ref().unwrap();
                assert!(li.leap59);
                assert!(!li.leap61);
                assert!(!li.pastleap59);
                assert!(li.pastleap61);
                assert_eq!(ta.ncr_base, 0x0000_AAAA_AAAA);
                assert_eq!(ta.ncr_ext, 0x1AA);
                assert_eq!(ta.association_timestamp_seconds, 0x12345678_9ABCDEF0);
                assert_eq!(ta.association_timestamp_nanoseconds, 0xDEADBEEF);
            }
            other => panic!("expected TimeAssociation, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact re-serialize");
    }

    #[test]
    fn position_v2_orbital_round_trip() {
        let body = SatBody::PositionV2(PositionV2Body {
            satellites: vec![PositionV2Satellite {
                satellite_id: 0x123456,
                position: PositionSystem::Orbital {
                    orbital_position: 0x1234,
                    west_east_flag: true,
                },
            }],
        });
        let bytes = build_sat(0, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::PositionV2(pv2) => {
                assert_eq!(pv2.satellites.len(), 1);
                assert_eq!(pv2.satellites[0].satellite_id, 0x123456);
                match &pv2.satellites[0].position {
                    PositionSystem::Orbital {
                        orbital_position,
                        west_east_flag,
                    } => {
                        assert_eq!(*orbital_position, 0x1234);
                        assert!(*west_east_flag);
                    }
                    other => panic!("expected Orbital, got {other:?}"),
                }
            }
            other => panic!("expected PositionV2, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact re-serialize");
    }

    #[test]
    fn beamhopping_mode0_round_trip() {
        let body = SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
            plans: vec![BeamhoppingPlan {
                beamhopping_time_plan_id: 0xDEADBEEF,
                time_plan_mode: 0,
                time_of_application_base: 0x0000_AAAA_AAAA,
                time_of_application_ext: 0x100,
                cycle_duration_base: 0x0000_5555_5555,
                cycle_duration_ext: 0x080,
                mode: BeamhoppingMode::Mode0 {
                    dwell_duration_base: 0x0000_1111_1111,
                    dwell_duration_ext: 0x111,
                    on_time_base: 0x0000_2222_2222,
                    on_time_ext: 0x222,
                },
            }],
        });
        let bytes = build_sat(3, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::BeamhoppingTimePlan(bhp) => {
                assert_eq!(bhp.plans.len(), 1);
                assert_eq!(bhp.plans[0].beamhopping_time_plan_id, 0xDEADBEEF);
                assert_eq!(bhp.plans[0].time_plan_mode, 0);
                match &bhp.plans[0].mode {
                    BeamhoppingMode::Mode0 {
                        dwell_duration_base,
                        ..
                    } => {
                        assert_eq!(*dwell_duration_base, 0x0000_1111_1111);
                    }
                    other => panic!("expected Mode0, got {other:?}"),
                }
            }
            other => panic!("expected BeamhoppingTimePlan, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact re-serialize");
    }

    #[test]
    fn reserved_discriminant_has_no_kind() {
        let bytes = build_sat(7, 0, &SatBody::Raw(Vec::new()));
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 7);
        assert_eq!(sat.kind(), None);
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        let mut bytes = build_sat(0, 0, &SatBody::Raw(vec![1, 2, 3]));
        bytes[0] = 0x40;
        assert!(matches!(
            SatSection::parse(&bytes).unwrap_err(),
            Error::UnexpectedTableId { table_id: 0x40, .. }
        ));
    }

    #[test]
    fn rejects_short_buffer() {
        assert!(matches!(
            SatSection::parse(&[0x4D, 0xF0]).unwrap_err(),
            Error::BufferTooShort {
                what: "SatSection",
                ..
            }
        ));
    }

    #[test]
    fn serialize_round_trip_raw() {
        let body_data = vec![0x01, 0x02, 0x03, 0x04, 0x05];
        let sat = SatSection {
            satellite_table_id: 10,
            private_indicator: true,
            table_count: 0x2FF,
            version_number: 5,
            current_next_indicator: true,
            section_number: 0,
            last_section_number: 0,
            body: SatBody::Raw(body_data.clone()),
        };
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        let re = SatSection::parse(&buf).unwrap();
        assert_eq!(re.body, SatBody::Raw(body_data));
        assert_eq!(re.table_count, 0x2FF);
    }

    #[test]
    fn parse_handwritten_sat_raw() {
        let mut bytes: Vec<u8> = vec![
            0x4D, 0xF0, 0x0E, 0x1C, 0x00, 0xCB, 0x00, 0x00, 0x00, 0xAA, 0xBB, 0xCC, 0xDD,
        ];
        let crc = dvb_common::crc32_mpeg2::compute(&bytes);
        bytes.extend_from_slice(&crc.to_be_bytes());
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 7);
        assert_eq!(sat.table_count, 0);
        assert_eq!(sat.version_number, 5);
        assert!(sat.current_next_indicator);
        match sat.body {
            SatBody::Raw(v) => assert_eq!(v, &[0xAA, 0xBB, 0xCC, 0xDD]),
            other => panic!("expected Raw, got {other:?}"),
        }
    }

    #[test]
    fn beamhopping_multi_plan_round_trip() {
        let body = SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
            plans: vec![
                BeamhoppingPlan {
                    beamhopping_time_plan_id: 0x11111111,
                    time_plan_mode: 0,
                    time_of_application_base: 0x0000_AAAA_AAAA,
                    time_of_application_ext: 0x100,
                    cycle_duration_base: 0x0000_5555_5555,
                    cycle_duration_ext: 0x080,
                    mode: BeamhoppingMode::Mode0 {
                        dwell_duration_base: 0x0000_1111_1111,
                        dwell_duration_ext: 0x111,
                        on_time_base: 0x0000_2222_2222,
                        on_time_ext: 0x222,
                    },
                },
                BeamhoppingPlan {
                    beamhopping_time_plan_id: 0x22222222,
                    time_plan_mode: 0,
                    time_of_application_base: 0x0000_BBBB_BBBB,
                    time_of_application_ext: 0x200,
                    cycle_duration_base: 0x0000_6666_6666,
                    cycle_duration_ext: 0x090,
                    mode: BeamhoppingMode::Mode0 {
                        dwell_duration_base: 0x0000_3333_3333,
                        dwell_duration_ext: 0x333,
                        on_time_base: 0x0000_4444_4444,
                        on_time_ext: 0x444,
                    },
                },
            ],
        });
        let bytes = build_sat(3, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::BeamhoppingTimePlan(bhp) => {
                assert_eq!(bhp.plans.len(), 2);
                assert_eq!(bhp.plans[0].beamhopping_time_plan_id, 0x11111111);
                assert_eq!(bhp.plans[1].beamhopping_time_plan_id, 0x22222222);
            }
            other => panic!("expected BeamhoppingTimePlan, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact multi-plan round-trip");
    }

    #[test]
    fn position_v3_one_sat_with_metadata_round_trip() {
        let body = SatBody::PositionV3(PositionV3Body {
            oem_version_major: 2,
            oem_version_minor: 1,
            creation_date_year: 26,
            creation_date_day: 42,
            creation_date_day_fraction: 0,
            satellites: vec![PositionV3Satellite {
                satellite_id: 0xABCDEF,
                usable_start_time_flag: true,
                usable_stop_time_flag: false,
                ephemeris_accel_flag: false,
                covariance_flag: false,
                metadata: Some(PositionV3Metadata {
                    total_start_time_year: 26,
                    total_start_time_day: 1,
                    total_start_time_day_fraction: 0,
                    total_stop_time_year: 27,
                    total_stop_time_day: 100,
                    total_stop_time_day_fraction: 0,
                    interpolation_flag: true,
                    interpolation_type: InterpolationType::Linear,
                    interpolation_degree: 2,
                    usable_start_time: Some(UsableTime {
                        year: 26,
                        day: 10,
                        day_fraction: 0,
                    }),
                    usable_stop_time: None,
                }),
                ephemeris_data: Vec::new(),
                covariance: None,
            }],
        });
        let bytes = build_sat(4, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::PositionV3(v3) => {
                assert_eq!(v3.satellites.len(), 1);
                assert_eq!(v3.satellites[0].satellite_id, 0xABCDEF);
                let md = v3.satellites[0].metadata.as_ref().unwrap();
                assert!(md.interpolation_flag);
                assert_eq!(md.interpolation_type, InterpolationType::Linear);
                assert_eq!(md.interpolation_degree, 2);
                assert!(md.usable_start_time.is_some());
            }
            other => panic!("expected PositionV3, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact PositionV3 round-trip");
    }

    #[test]
    fn cell_fragment_round_trip() {
        let body = SatBody::CellFragment(CellFragmentBody {
            fragments: vec![CellFragment {
                cell_fragment_id: 0x11223344,
                first_occurrence: true,
                last_occurrence: false,
                center: Some(CellCenter {
                    center_latitude: 1000,
                    center_longitude: -2000,
                    max_distance: 500000,
                }),
                delivery_system_ids: vec![0x55667788],
                new_delivery_systems: vec![NewDeliverySystem {
                    new_delivery_system_id: 0xAABBCCDD,
                    time_of_application_base: 0x0000_1234_5678,
                    time_of_application_ext: 0x100,
                }],
                obsolescent_delivery_systems: vec![ObsolescentDeliverySystem {
                    obsolescent_delivery_system_id: 0xEEFF0011,
                    time_of_obsolescence_base: 0x0000_9ABC_DEF0,
                    time_of_obsolescence_ext: 0x1FF,
                }],
            }],
        });
        let bytes = build_sat(1, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::CellFragment(cf) => {
                assert_eq!(cf.fragments.len(), 1);
                assert_eq!(cf.fragments[0].cell_fragment_id, 0x11223344);
                assert!(cf.fragments[0].first_occurrence);
                assert!(cf.fragments[0].center.is_some());
                assert_eq!(cf.fragments[0].delivery_system_ids.len(), 1);
                assert_eq!(cf.fragments[0].new_delivery_systems.len(), 1);
                assert_eq!(cf.fragments[0].obsolescent_delivery_systems.len(), 1);
            }
            other => panic!("expected CellFragment, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact CellFragment round-trip");
    }

    #[test]
    fn beamhopping_mode1_round_trip() {
        let body = SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
            plans: vec![BeamhoppingPlan {
                beamhopping_time_plan_id: 0x12345678,
                time_plan_mode: 1,
                time_of_application_base: 0x0000_AAAA_AAAA,
                time_of_application_ext: 0x100,
                cycle_duration_base: 0x0000_5555_5555,
                cycle_duration_ext: 0x080,
                mode: BeamhoppingMode::Mode1 {
                    bit_map_size: 8,
                    current_slot: 3,
                    slot_transmission_on: vec![true, false, true, true, false, false, true, false],
                },
            }],
        });
        let bytes = build_sat(3, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::BeamhoppingTimePlan(bhp) => {
                assert_eq!(bhp.plans.len(), 1);
                assert_eq!(bhp.plans[0].time_plan_mode, 1);
                match &bhp.plans[0].mode {
                    BeamhoppingMode::Mode1 {
                        bit_map_size,
                        current_slot,
                        slot_transmission_on,
                    } => {
                        assert_eq!(*bit_map_size, 8);
                        assert_eq!(*current_slot, 3);
                        assert_eq!(
                            slot_transmission_on,
                            &[true, false, true, true, false, false, true, false]
                        );
                    }
                    other => panic!("expected Mode1, got {other:?}"),
                }
            }
            other => panic!("expected BeamhoppingTimePlan, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact Mode1 round-trip");
    }

    #[test]
    fn beamhopping_mode2_round_trip() {
        let body = SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
            plans: vec![BeamhoppingPlan {
                beamhopping_time_plan_id: 0x87654321,
                time_plan_mode: 2,
                time_of_application_base: 0x0000_BBBB_BBBB,
                time_of_application_ext: 0x200,
                cycle_duration_base: 0x0000_6666_6666,
                cycle_duration_ext: 0x090,
                mode: BeamhoppingMode::Mode2 {
                    grid_size_base: 0x0000_1111_1111,
                    grid_size_ext: 0x111,
                    revisit_duration_base: 0x0000_2222_2222,
                    revisit_duration_ext: 0x222,
                    sleep_time_base: 0x0000_3333_3333,
                    sleep_time_ext: 0x333,
                    sleep_duration_base: 0x0000_4444_4444,
                    sleep_duration_ext: 0x444,
                },
            }],
        });
        let bytes = build_sat(3, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::BeamhoppingTimePlan(bhp) => {
                assert_eq!(bhp.plans.len(), 1);
                assert_eq!(bhp.plans[0].time_plan_mode, 2);
                match &bhp.plans[0].mode {
                    BeamhoppingMode::Mode2 { grid_size_base, .. } => {
                        assert_eq!(*grid_size_base, 0x0000_1111_1111);
                    }
                    other => panic!("expected Mode2, got {other:?}"),
                }
            }
            other => panic!("expected BeamhoppingTimePlan, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact Mode2 round-trip");
    }

    #[test]
    fn beamhopping_reserved_mode_round_trip() {
        let body = SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
            plans: vec![
                BeamhoppingPlan {
                    beamhopping_time_plan_id: 0x11111111,
                    time_plan_mode: 0,
                    time_of_application_base: 0x0000_AAAA_AAAA,
                    time_of_application_ext: 0x100,
                    cycle_duration_base: 0x0000_5555_5555,
                    cycle_duration_ext: 0x080,
                    mode: BeamhoppingMode::Mode0 {
                        dwell_duration_base: 0x0000_1111_1111,
                        dwell_duration_ext: 0x111,
                        on_time_base: 0x0000_2222_2222,
                        on_time_ext: 0x222,
                    },
                },
                BeamhoppingPlan {
                    beamhopping_time_plan_id: 0x22222222,
                    time_plan_mode: 3,
                    time_of_application_base: 0x0000_CCCC_CCCC,
                    time_of_application_ext: 0x300,
                    cycle_duration_base: 0x0000_DDDD_DDDD,
                    cycle_duration_ext: 0x400,
                    mode: BeamhoppingMode::Reserved(vec![0xAA, 0xBB, 0xCC]),
                },
            ],
        });
        let bytes = build_sat(3, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::BeamhoppingTimePlan(bhp) => {
                assert_eq!(bhp.plans.len(), 2);
                assert_eq!(bhp.plans[0].time_plan_mode, 0);
                assert_eq!(bhp.plans[1].time_plan_mode, 3);
                match &bhp.plans[1].mode {
                    BeamhoppingMode::Reserved(v) => {
                        assert_eq!(v, &[0xAA, 0xBB, 0xCC]);
                    }
                    other => panic!("expected Reserved, got {other:?}"),
                }
            }
            other => panic!("expected BeamhoppingTimePlan, got {other:?}"),
        }
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2, "byte-exact Reserved mode round-trip");
    }

    #[test]
    fn cell_fragment_truncated_dsid_count() {
        let body = SatBody::CellFragment(CellFragmentBody {
            fragments: vec![CellFragment {
                cell_fragment_id: 1,
                first_occurrence: false,
                last_occurrence: false,
                center: None,
                delivery_system_ids: vec![0x11111111],
                new_delivery_systems: Vec::new(),
                obsolescent_delivery_systems: Vec::new(),
            }],
        });
        let bytes = build_sat(1, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        let mut buf2 = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf2).unwrap();
        assert_eq!(bytes, buf2);

        let corrupt_sat = SatSection {
            satellite_table_id: 1,
            private_indicator: true,
            table_count: 0,
            version_number: 5,
            current_next_indicator: true,
            section_number: 0,
            last_section_number: 0,
            body: SatBody::CellFragment(CellFragmentBody {
                fragments: vec![CellFragment {
                    cell_fragment_id: 1,
                    first_occurrence: false,
                    last_occurrence: false,
                    center: None,
                    delivery_system_ids: vec![0x11111111; 50],
                    new_delivery_systems: Vec::new(),
                    obsolescent_delivery_systems: Vec::new(),
                }],
            }),
        };
        let mut corrupt_buf = vec![0u8; corrupt_sat.serialized_len()];
        corrupt_sat.serialize_into(&mut corrupt_buf).unwrap();
        let section_length = (corrupt_buf.len() - SECTION_LENGTH_PREFIX) as u16;
        corrupt_buf[1] = 0x80 | 0x40 | 0x30 | ((section_length >> 8) as u8 & 0x0F);
        corrupt_buf[2] = (section_length & 0xFF) as u8;
        let crc_end = corrupt_buf.len();
        let crc = dvb_common::crc32_mpeg2::compute(&corrupt_buf[..crc_end - CRC_LEN]);
        corrupt_buf[crc_end - CRC_LEN..crc_end].copy_from_slice(&crc.to_be_bytes());
        let original_len = corrupt_buf.len();
        corrupt_buf.truncate(original_len - 100);
        let sl = (corrupt_buf.len() - SECTION_LENGTH_PREFIX) as u16;
        corrupt_buf[1] = (corrupt_buf[1] & 0xF0) | ((sl >> 8) as u8 & 0x0F);
        corrupt_buf[2] = (sl & 0xFF) as u8;
        let crc_end = corrupt_buf.len();
        let crc2 = dvb_common::crc32_mpeg2::compute(&corrupt_buf[..crc_end - CRC_LEN]);
        corrupt_buf[crc_end - CRC_LEN..crc_end].copy_from_slice(&crc2.to_be_bytes());
        assert!(SatSection::parse(&corrupt_buf).is_err());
    }

    #[test]
    fn beamhopping_mode1_truncated_bit_map_size() {
        let corrupt_sat = SatSection {
            satellite_table_id: 3,
            private_indicator: true,
            table_count: 0,
            version_number: 5,
            current_next_indicator: true,
            section_number: 0,
            last_section_number: 0,
            body: SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
                plans: vec![BeamhoppingPlan {
                    beamhopping_time_plan_id: 1,
                    time_plan_mode: 1,
                    time_of_application_base: 0,
                    time_of_application_ext: 0,
                    cycle_duration_base: 0,
                    cycle_duration_ext: 0,
                    mode: BeamhoppingMode::Mode1 {
                        bit_map_size: 200,
                        current_slot: 0,
                        slot_transmission_on: vec![true; 200],
                    },
                }],
            }),
        };
        let mut corrupt_buf = vec![0u8; corrupt_sat.serialized_len()];
        corrupt_sat.serialize_into(&mut corrupt_buf).unwrap();
        let original_len = corrupt_buf.len();
        let truncate_at = HEADER_LEN + 20;
        assert!(
            truncate_at + CRC_LEN < original_len,
            "fixture must be large enough to truncate meaningfully"
        );
        {
            corrupt_buf.truncate(truncate_at + CRC_LEN);
            let sl = (corrupt_buf.len() - SECTION_LENGTH_PREFIX) as u16;
            corrupt_buf[1] = (corrupt_buf[1] & 0xF0) | ((sl >> 8) as u8 & 0x0F);
            corrupt_buf[2] = (sl & 0xFF) as u8;
            let crc_end = corrupt_buf.len();
            let crc = dvb_common::crc32_mpeg2::compute(&corrupt_buf[..crc_end - CRC_LEN]);
            corrupt_buf[crc_end - CRC_LEN..crc_end].copy_from_slice(&crc.to_be_bytes());
            assert!(SatSection::parse(&corrupt_buf).is_err());
        }
    }

    #[test]
    fn position_v3_truncated_ephemeris_data_count() {
        let corrupt_sat = SatSection {
            satellite_table_id: 4,
            private_indicator: true,
            table_count: 0,
            version_number: 5,
            current_next_indicator: true,
            section_number: 0,
            last_section_number: 0,
            body: SatBody::PositionV3(PositionV3Body {
                oem_version_major: 1,
                oem_version_minor: 0,
                creation_date_year: 25,
                creation_date_day: 1,
                creation_date_day_fraction: 0,
                satellites: vec![PositionV3Satellite {
                    satellite_id: 1,
                    usable_start_time_flag: false,
                    usable_stop_time_flag: false,
                    ephemeris_accel_flag: false,
                    covariance_flag: false,
                    metadata: None,
                    ephemeris_data: vec![
                        EphemerisData {
                            epoch_year: 25,
                            epoch_day: 1,
                            epoch_day_fraction: 0,
                            ephemeris_x: 0,
                            ephemeris_y: 0,
                            ephemeris_z: 0,
                            ephemeris_x_dot: 0,
                            ephemeris_y_dot: 0,
                            ephemeris_z_dot: 0,
                            acceleration: None,
                        };
                        5
                    ],
                    covariance: None,
                }],
            }),
        };
        let mut corrupt_buf = vec![0u8; corrupt_sat.serialized_len()];
        corrupt_sat.serialize_into(&mut corrupt_buf).unwrap();
        let original_len = corrupt_buf.len();
        let truncate_at = HEADER_LEN + 30;
        assert!(
            truncate_at + CRC_LEN < original_len,
            "fixture must be large enough to truncate meaningfully"
        );
        {
            corrupt_buf.truncate(truncate_at + CRC_LEN);
            let sl = (corrupt_buf.len() - SECTION_LENGTH_PREFIX) as u16;
            corrupt_buf[1] = (corrupt_buf[1] & 0xF0) | ((sl >> 8) as u8 & 0x0F);
            corrupt_buf[2] = (sl & 0xFF) as u8;
            let crc_end = corrupt_buf.len();
            let crc = dvb_common::crc32_mpeg2::compute(&corrupt_buf[..crc_end - CRC_LEN]);
            corrupt_buf[crc_end - CRC_LEN..crc_end].copy_from_slice(&crc.to_be_bytes());
            assert!(SatSection::parse(&corrupt_buf).is_err());
        }
    }

    #[test]
    fn hand_byte_time_association() {
        let body = SatBody::TimeAssociation(TimeAssociationBody {
            association_type: AssociationType::UtcWithoutLeap,
            leap_info: None,
            ncr_base: 0x0000_AAAA_AAAA_u64,
            ncr_ext: 0x1AA,
            association_timestamp_seconds: 0,
            association_timestamp_nanoseconds: 0,
        });
        let bytes = build_sat(2, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 2);
        match &sat.body {
            SatBody::TimeAssociation(ta) => {
                assert_eq!(ta.association_type, AssociationType::UtcWithoutLeap);
                assert_eq!(ta.ncr_base, 0x0000_AAAA_AAAA);
                assert_eq!(ta.ncr_ext, 0x1AA);
            }
            other => panic!("expected TimeAssociation, got {other:?}"),
        }
        assert_eq!((bytes[1] >> 6) & 1, 1);
        assert_eq!((bytes[3] >> 2) & 0x3F, 2);
    }

    #[test]
    fn hand_byte_position_v2_orbital() {
        let body = SatBody::PositionV2(PositionV2Body {
            satellites: vec![PositionV2Satellite {
                satellite_id: 0x010203,
                position: PositionSystem::Orbital {
                    orbital_position: 0x1920,
                    west_east_flag: true,
                },
            }],
        });
        let bytes = build_sat(0, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::PositionV2(pv2) => {
                assert_eq!(pv2.satellites[0].satellite_id, 0x010203);
                match &pv2.satellites[0].position {
                    PositionSystem::Orbital {
                        orbital_position, ..
                    } => {
                        assert_eq!(*orbital_position, 0x1920);
                    }
                    other => panic!("expected Orbital, got {other:?}"),
                }
            }
            other => panic!("expected PositionV2, got {other:?}"),
        }
        assert_eq!((bytes[3] >> 2) & 0x3F, 0);
    }

    #[test]
    fn hand_byte_cell_fragment() {
        let body = SatBody::CellFragment(CellFragmentBody {
            fragments: vec![CellFragment {
                cell_fragment_id: 0xAABBCCDD,
                first_occurrence: false,
                last_occurrence: true,
                center: None,
                delivery_system_ids: Vec::new(),
                new_delivery_systems: Vec::new(),
                obsolescent_delivery_systems: Vec::new(),
            }],
        });
        let bytes = build_sat(1, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::CellFragment(cf) => {
                assert_eq!(cf.fragments[0].cell_fragment_id, 0xAABBCCDD);
                assert!(cf.fragments[0].last_occurrence);
            }
            other => panic!("expected CellFragment, got {other:?}"),
        }
        assert_eq!((bytes[3] >> 2) & 0x3F, 1);
    }

    #[test]
    fn hand_byte_beamhopping_mode0() {
        let body = SatBody::BeamhoppingTimePlan(BeamhoppingTimePlanBody {
            plans: vec![BeamhoppingPlan {
                beamhopping_time_plan_id: 0xDEADBEEF,
                time_plan_mode: 0,
                time_of_application_base: 0,
                time_of_application_ext: 0,
                cycle_duration_base: 0,
                cycle_duration_ext: 0,
                mode: BeamhoppingMode::Mode0 {
                    dwell_duration_base: 0,
                    dwell_duration_ext: 0,
                    on_time_base: 0,
                    on_time_ext: 0,
                },
            }],
        });
        let bytes = build_sat(3, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::BeamhoppingTimePlan(bhp) => {
                assert_eq!(bhp.plans[0].beamhopping_time_plan_id, 0xDEADBEEF);
                assert_eq!(bhp.plans[0].time_plan_mode, 0);
            }
            other => panic!("expected BeamhoppingTimePlan, got {other:?}"),
        }
        assert_eq!((bytes[3] >> 2) & 0x3F, 3);
    }

    #[test]
    fn hand_byte_position_v3() {
        let body = SatBody::PositionV3(PositionV3Body {
            oem_version_major: 1,
            oem_version_minor: 2,
            creation_date_year: 26,
            creation_date_day: 42,
            creation_date_day_fraction: 0,
            satellites: Vec::new(),
        });
        let bytes = build_sat(4, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        match &sat.body {
            SatBody::PositionV3(v3) => {
                assert_eq!(v3.oem_version_major, 1);
                assert_eq!(v3.oem_version_minor, 2);
            }
            other => panic!("expected PositionV3, got {other:?}"),
        }
        assert_eq!((bytes[3] >> 2) & 0x3F, 4);
    }

    // ── Hand-built byte-literal anchor tests ──────────────────────────────────
    // Each constructs a wire byte array by hand (no serializer) and verifies
    // that the bit-packed parser maps fields to the expected bit positions.
    // Re-serialization must then produce byte-identical output.

    fn crc_section(bytes: &[u8]) -> Vec<u8> {
        let mut v = bytes.to_vec();
        let crc = dvb_common::crc32_mpeg2::compute(&v);
        v.extend_from_slice(&crc.to_be_bytes());
        v
    }

    #[test]
    fn hand_built_time_association_anchor() {
        // section_length = body_len(19) + 10 = 29 = 0x001D
        // Bit breakdown in body (association_type=0, ncr_base=1, all else 0):
        //   [0:3]   association_type(4)=0
        //   [4:7]   reserved/ncr_leap(4)=0
        //   [8:40]  ncr_base(33)=1    →  LSB lands at bit 40 → byte 5 bit 7
        //   [41:46] skip(6)
        //   [47:55] ncr_ext(9)=0
        //   [56:119] timestamp_seconds(64)=0
        //   [120:151] timestamp_nanoseconds(32)=0
        let bytes = crc_section(&[
            0x4D, 0xF0, 0x1D, 0x08, 0x00, 0xCB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ]);
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 2);
        match &sat.body {
            SatBody::TimeAssociation(ta) => {
                assert_eq!(ta.association_type, AssociationType::UtcWithoutLeap);
                assert_eq!(ta.ncr_base, 1);
                assert_eq!(ta.ncr_ext, 0);
                assert_eq!(ta.association_timestamp_seconds, 0);
                assert_eq!(ta.association_timestamp_nanoseconds, 0);
            }
            other => panic!("expected TimeAssociation, got {other:?}"),
        }
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes, "byte-identical re-serialize");
    }

    #[test]
    fn hand_built_position_v2_orbital_anchor() {
        // section_length = body_len(7) + 10 = 17 = 0x0011
        // Bit breakdown in body (one satellite, orbital position):
        //   [0:23]   satellite_id(24)=0x010203
        //   [24:30]  skip(7)
        //   [31]     position_system(1)=0 → orbital
        //   [32:47]  orbital_position(16)=0x1234
        //   [48]     west_east_flag(1)=1
        //   [49:55]  skip(7)
        let bytes = crc_section(&[
            0x4D, 0xF0, 0x11, 0x00, 0x00, 0xCB, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x00, 0x12,
            0x34, 0x80,
        ]);
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 0);
        match &sat.body {
            SatBody::PositionV2(pv2) => {
                assert_eq!(pv2.satellites.len(), 1);
                let s = &pv2.satellites[0];
                assert_eq!(s.satellite_id, 0x010203);
                match &s.position {
                    PositionSystem::Orbital {
                        orbital_position,
                        west_east_flag,
                    } => {
                        assert_eq!(*orbital_position, 0x1234);
                        assert!(*west_east_flag);
                    }
                    other => panic!("expected Orbital, got {other:?}"),
                }
            }
            other => panic!("expected PositionV2, got {other:?}"),
        }
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes, "byte-identical re-serialize");
    }

    #[test]
    fn hand_built_cell_fragment_anchor() {
        // section_length = body_len(10) + 10 = 20 = 0x0014
        // Bit breakdown in body (one fragment, no center, empty lists):
        //   [0:31]   cell_fragment_id(32)=0xAABBCCDD
        //   [32]     first_occurrence(1)=0
        //   [33]     last_occurrence(1)=1
        //   [34:37]  skip(4)
        //   [38:47]  delivery_system_ids_count(10)=0
        //   [48:53]  skip(6)
        //   [54:63]  new_delivery_systems_count(10)=0
        //   [64:69]  skip(6)
        //   [70:79]  obsolescent_delivery_systems_count(10)=0
        let bytes = crc_section(&[
            0x4D, 0xF0, 0x14, 0x04, 0x00, 0xCB, 0x00, 0x00, 0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0x40,
            0x00, 0x00, 0x00, 0x00, 0x00,
        ]);
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 1);
        match &sat.body {
            SatBody::CellFragment(cf) => {
                assert_eq!(cf.fragments.len(), 1);
                let f = &cf.fragments[0];
                assert_eq!(f.cell_fragment_id, 0xAABBCCDD);
                assert!(!f.first_occurrence);
                assert!(f.last_occurrence);
                assert!(f.center.is_none());
                assert!(f.delivery_system_ids.is_empty());
                assert!(f.new_delivery_systems.is_empty());
                assert!(f.obsolescent_delivery_systems.is_empty());
            }
            other => panic!("expected CellFragment, got {other:?}"),
        }
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes, "byte-identical re-serialize");
    }

    #[test]
    fn hand_built_beamhopping_mode0_anchor() {
        // section_length = body_len(31) + 10 = 41 = 0x0029
        // Bit breakdown in body (one plan, Mode0, all times zero):
        //   [0:31]   plan_id(32)=0xDEADBEEF
        //   [32:35]  skip(4)
        //   [36:47]  plan_length(12)=25 → 0x019
        //   [48:53]  skip(6)
        //   [54:55]  plan_mode(2)=0
        //   [56:247] all zero (times, durations)
        let bytes = crc_section(&[
            0x4D, 0xF0, 0x29, 0x0C, 0x00, 0xCB, 0x00, 0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF, 0x00,
            0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ]);
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 3);
        match &sat.body {
            SatBody::BeamhoppingTimePlan(bhp) => {
                assert_eq!(bhp.plans.len(), 1);
                let p = &bhp.plans[0];
                assert_eq!(p.beamhopping_time_plan_id, 0xDEADBEEF);
                assert_eq!(p.time_plan_mode, 0);
                assert_eq!(p.time_of_application_base, 0);
                assert_eq!(p.cycle_duration_base, 0);
                match &p.mode {
                    BeamhoppingMode::Mode0 {
                        dwell_duration_base,
                        dwell_duration_ext,
                        on_time_base,
                        on_time_ext,
                    } => {
                        assert_eq!(*dwell_duration_base, 0);
                        assert_eq!(*dwell_duration_ext, 0);
                        assert_eq!(*on_time_base, 0);
                        assert_eq!(*on_time_ext, 0);
                    }
                    other => panic!("expected Mode0, got {other:?}"),
                }
            }
            other => panic!("expected BeamhoppingTimePlan, got {other:?}"),
        }
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes, "byte-identical re-serialize");
    }

    #[test]
    fn hand_built_position_v3_anchor() {
        // section_length = body_len(8) + 10 = 18 = 0x0012
        // Bit breakdown in body (empty satellites):
        //   [0:3]   oem_version_major(4)=1
        //   [4:7]   oem_version_minor(4)=2        → byte 0 = 0x12
        //   [8:15]  creation_date_year(8)=26       → byte 1 = 0x1A
        //   [16:22] skip(7)
        //   [23:31] creation_date_day(9)=42        → byte 2 bit 0=0, byte 3 = 0x2A
        //   [32:63] creation_date_day_fraction(32)=0 → bytes 4-7
        let bytes = crc_section(&[
            0x4D, 0xF0, 0x12, 0x10, 0x00, 0xCB, 0x00, 0x00, 0x00, 0x12, 0x1A, 0x00, 0x2A, 0x00,
            0x00, 0x00, 0x00,
        ]);
        let sat = SatSection::parse(&bytes).unwrap();
        assert_eq!(sat.satellite_table_id, 4);
        match &sat.body {
            SatBody::PositionV3(v3) => {
                assert_eq!(v3.oem_version_major, 1);
                assert_eq!(v3.oem_version_minor, 2);
                assert_eq!(v3.creation_date_year, 26);
                assert_eq!(v3.creation_date_day, 42);
                assert_eq!(v3.creation_date_day_fraction, 0);
                assert!(v3.satellites.is_empty());
            }
            other => panic!("expected PositionV3, got {other:?}"),
        }
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes, "byte-identical re-serialize");
    }

    #[test]
    fn parse_rejects_truncated_time_association_body() {
        let body = SatBody::TimeAssociation(TimeAssociationBody {
            association_type: AssociationType::UtcWithoutLeap,
            leap_info: None,
            ncr_base: 0,
            ncr_ext: 0,
            association_timestamp_seconds: 0,
            association_timestamp_nanoseconds: 0,
        });
        let bytes = build_sat(2, 0, &body);
        let sat = SatSection::parse(&bytes).unwrap();
        let mut buf = vec![0u8; sat.serialized_len()];
        sat.serialize_into(&mut buf).unwrap();
        buf.truncate(HEADER_LEN + 4 + CRC_LEN);
        let sl = (buf.len() - SECTION_LENGTH_PREFIX) as u16;
        buf[1] = (buf[1] & 0xF0) | ((sl >> 8) as u8 & 0x0F);
        buf[2] = (sl & 0xFF) as u8;
        let crc_end = buf.len();
        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_end - CRC_LEN]);
        buf[crc_end - CRC_LEN..crc_end].copy_from_slice(&crc.to_be_bytes());
        assert!(SatSection::parse(&buf).is_err());
    }
}