falcon_mdf 0.7.1

High-performance Rust library for reading ASAM MDF v4 (MF4) measurement data files
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
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
//! Signal abstraction for reading decoded channel data.
//!
//! The Signal type provides efficient access to channel samples,
//! supporting both eager and lazy decoding strategies.

use crate::blocks::{ChannelType, Conversion, ConversionInput, ConversionOutput, DataType};
use crate::error::{Mf4Error, Result};
use crate::model::{
    CanopenDate, CanopenTime, Channel, MlsdLength, SignalValues, ValueKind, VlsdPayloads,
};
use crate::parser::binary::{bytes_to_f64, read_f32, read_f64, read_int, read_uint};
use std::sync::Arc;

/// Maps each row-major element position to where the record actually holds it,
/// for an array whose dimensions are stored in reverse order.
///
/// Row-major means the last dimension varies fastest; an inverse-layout file
/// stores the first varying fastest. Decomposing the output position into
/// per-dimension indices and re-weighting them by the stored strides converts
/// between the two — which is a transpose in the two-dimensional case.
///
/// `pub(crate)` so [`crate::file`]'s look-up-composed-with-CA resolution (B30)
/// can apply the same per-level transpose without duplicating it.
pub(crate) fn row_major_to_stored(dims: &[u64], count: usize) -> Vec<usize> {
    // Stored stride of dimension j is the product of every dimension before it.
    let mut stored_stride = Vec::with_capacity(dims.len());
    let mut acc = 1usize;
    for &d in dims {
        stored_stride.push(acc);
        acc = acc.saturating_mul(d as usize);
    }

    (0..count)
        .map(|k| {
            let mut rem = k;
            let mut at = 0usize;
            for j in (0..dims.len()).rev() {
                let d = (dims[j] as usize).max(1);
                at += (rem % d) * stored_stride[j];
                rem /= d;
            }
            at
        })
        .collect()
}

/// Byte offset of a record's invalidation area for sample `index`.
fn i_offset(layout: &RecordLayout, index: usize) -> usize {
    index * layout.record_size + layout.record_offset + layout.inval_start
}

/// Decodes one array element at `offset` within `raw_data` to `f64`, honouring the
/// element's declared type and conversion.
fn read_element_from_bytes(
    raw_data: &[u8],
    elem: &crate::model::ArrayElement,
    offset: usize,
    conversion: &Conversion,
    channel_is_float: bool,
) -> f64 {
    if !elem.data_type.is_numeric() {
        return f64::NAN;
    }

    let le = elem.data_type.is_little_endian();
    let raw = if elem.data_type.is_float() {
        let bits = read_uint(raw_data, offset, elem.bit_offset, elem.bit_count, le);
        if elem.bit_count <= 32 {
            f32::from_bits(bits as u32) as f64
        } else {
            f64::from_bits(bits)
        }
    } else if elem.data_type.is_signed() {
        read_int(raw_data, offset, elem.bit_offset, elem.bit_count, le) as f64
    } else {
        read_uint(raw_data, offset, elem.bit_offset, elem.bit_count, le) as f64
    };

    conversion.convert(raw, channel_is_float)
}

/// Decodes one text sample, honouring the channel's declared encoding.
///
/// MF4 pads fixed-width text fields with NUL bytes, so trailing NULs are part of
/// the container rather than the value and are trimmed.
fn decode_string(bytes: &[u8], data_type: DataType) -> String {
    match data_type {
        DataType::StringUtf16Le | DataType::StringUtf16Be => {
            let big_endian = data_type == DataType::StringUtf16Be;
            let units: Vec<u16> = bytes
                .chunks_exact(2)
                .map(|c| {
                    if big_endian {
                        u16::from_be_bytes([c[0], c[1]])
                    } else {
                        u16::from_le_bytes([c[0], c[1]])
                    }
                })
                .take_while(|&u| u != 0)
                .collect();
            String::from_utf16_lossy(&units)
        }
        DataType::StringSbc => {
            // ISO-8859-1, where every byte is its own code point. That makes
            // the conversion a widening cast rather than a decode — but it is
            // not the same as UTF-8: byte 0xD6 is Ö here and the start of a
            // two-byte sequence there.
            let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
            bytes[..end].iter().map(|&b| b as char).collect()
        }
        _ => {
            let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
            String::from_utf8_lossy(&bytes[..end]).into_owned()
        }
    }
}

/// How records are laid out in a signal's raw buffer.
#[derive(Debug, Clone, Copy)]
pub(crate) struct RecordLayout {
    /// Stride from one record to the next.
    pub record_size: usize,
    /// Offset from a record's start to its payload, skipping any record ID.
    pub record_offset: usize,
    /// Offset from the payload start to the invalidation bytes, which the
    /// format places immediately after the channel data.
    pub inval_start: usize,
    /// Number of invalidation bytes per record; zero when the group has none.
    pub inval_bytes: usize,
}

/// Where a channel's field sits within a record, for strided reading.
#[derive(Debug, Clone, Copy)]
struct StridedField {
    /// Byte offset of the field from the start of the buffer.
    offset: usize,
    /// Bytes the field touches, including those its bit offset spills into.
    span: usize,
    /// Bits to shift right after reading, to bring the field to bit zero.
    bit_offset: u32,
    /// Width of the field in bits.
    bits: u32,
    /// Whether the field is whole bytes on a byte boundary, which needs no
    /// shifting or masking.
    aligned: bool,
}

impl StridedField {
    /// Reads this field from the start of one record.
    #[inline]
    fn read(&self, record: &[u8]) -> Option<u64> {
        let bytes = record.get(..self.span)?;

        // Standard widths need a single unaligned load, including packed
        // fields that span a standard width before shifting and masking.
        let mut raw = match bytes.len() {
            1 => bytes[0] as u64,
            2 => u16::from_le_bytes(bytes.try_into().ok()?) as u64,
            4 => u32::from_le_bytes(bytes.try_into().ok()?) as u64,
            8 => u64::from_le_bytes(bytes.try_into().ok()?),
            _ => bytes
                .iter()
                .enumerate()
                .fold(0u64, |value, (i, &b)| value | ((b as u64) << (i * 8))),
        };

        if self.aligned {
            return Some(raw);
        }

        raw >>= self.bit_offset;
        // A 64-bit field masks to all ones; shifting by 64 would overflow.
        let mask = if self.bits >= 64 {
            u64::MAX
        } else {
            (1u64 << self.bits) - 1
        };
        Some(raw & mask)
    }
}

/// A signal view for accessing decoded channel samples.
///
/// This type provides efficient access to the physical values of a channel,
/// handling raw data extraction, conversion, and optional caching.
///
/// # Example
/// ```ignore
/// let signal = file.signal(&channel)?;
/// println!("Sample count: {}", signal.len());
///
/// // Get all values as f64
/// let values = signal.values_f64()?;
/// for (i, value) in values.iter().enumerate() {
///     println!("Sample {}: {}", i, value);
/// }
/// ```
pub struct Signal {
    /// Channel metadata.
    pub(crate) channel: Channel,
    /// Raw record data for all samples.
    ///
    /// Shared rather than copied: every channel in a group reads the same
    /// records, and a group's records can be hundreds of megabytes.
    pub(crate) raw_data: Arc<Vec<u8>>,
    /// Record layout within `raw_data`.
    pub(crate) layout: RecordLayout,
    /// Number of samples.
    pub(crate) sample_count: usize,
    /// Payloads for a variable-length channel, absent for every other kind.
    pub(crate) payloads: Option<Arc<VlsdPayloads>>,
    /// Where a maximum-length channel's per-sample byte count lives, absent for
    /// every other kind.
    pub(crate) mlsd_length: Option<MlsdLength>,
    /// Where a dynamic-size array's one real per-sample element count lives,
    /// when [`Channel::array_dynamic_size`](crate::model::Channel) names a
    /// channel in this same record. `None` for every other channel, and for a
    /// dynamic-size array whose sizing channel could not be resolved — reading
    /// such a channel fails rather than using its declared maximum as if it
    /// were the shape.
    ///
    /// Reuses [`MlsdLength`]'s shape (byte offset, bit offset, bit count,
    /// endianness) rather than a type of its own: both describe the same
    /// thing, a small integer field elsewhere in the record giving a count.
    pub(crate) dynamic_array_length: Option<MlsdLength>,
    /// Member channel groups' record buffers for CG- or DG-template arrays.
    pub(crate) array_group_members: Option<Vec<ArrayGroupMember>>,
    /// Test-only switch forcing the general decode path.
    #[cfg(test)]
    pub(crate) force_general: bool,
}

/// Record data and layout for one member channel group in a CG- or DG-template array.
#[derive(Debug, Clone)]
pub(crate) struct ArrayGroupMember {
    pub raw_data: Arc<Vec<u8>>,
    pub layout: RecordLayout,
    pub sample_count: usize,
}

impl Signal {
    /// Creates a new Signal from raw data.
    pub(crate) fn new(
        channel: Channel,
        raw_data: Arc<Vec<u8>>,
        layout: RecordLayout,
        sample_count: usize,
    ) -> Self {
        Signal {
            channel,
            raw_data,
            layout,
            sample_count,
            payloads: None,
            mlsd_length: None,
            dynamic_array_length: None,
            array_group_members: None,
            #[cfg(test)]
            force_general: false,
        }
    }

    /// Supplies the payloads a variable-length channel refers to.
    pub(crate) fn attach_payloads(&mut self, payloads: Arc<VlsdPayloads>) {
        self.payloads = Some(payloads);
    }

    /// Supplies the member group buffers a CG- or DG-template array channel refers to.
    pub(crate) fn attach_array_group_members(&mut self, members: Vec<ArrayGroupMember>) {
        if let Some(first) = members.first() {
            self.sample_count = first.sample_count;
        }
        self.array_group_members = Some(members);
    }

    /// Supplies the field a maximum-length channel takes its sample sizes from.
    pub(crate) fn attach_mlsd_length(&mut self, length: MlsdLength) {
        self.mlsd_length = Some(length);
    }

    /// Supplies the field a dynamic-size array channel takes its real
    /// per-sample element count from.
    pub(crate) fn attach_dynamic_array_length(&mut self, length: MlsdLength) {
        self.dynamic_array_length = Some(length);
    }

    /// Returns which samples are valid, or `None` if the channel has no
    /// invalidation bit and every sample is therefore valid.
    ///
    /// `true` means the sample is valid. The file stores the opposite polarity —
    /// a set bit marks a sample *invalid* — which this method inverts so the
    /// result reads the way callers expect.
    ///
    /// Invalid samples are still present in [`Signal::values`]: they hold
    /// whatever bits the record contained, which is not a measurement. Check
    /// this before treating a channel's samples as data.
    pub fn validity(&self) -> Option<Vec<bool>> {
        // `cn_flags` bit 0 settles it for the whole channel, and settles it
        // without a per-sample bit or any invalidation bytes in the group — so
        // it has to be answered before the record is consulted at all.
        if self.channel.all_invalid {
            return Some(vec![false; self.sample_count]);
        }

        if !self.channel.invalidation_bit || self.layout.inval_bytes == 0 {
            return None;
        }

        let byte = (self.channel.inval_bit_pos / 8) as usize;
        let bit = self.channel.inval_bit_pos % 8;
        if byte >= self.layout.inval_bytes {
            // The declared bit lies outside the invalidation area; treating that
            // as "all valid" would invent data, so report no validity info.
            return None;
        }

        let mut out = Vec::with_capacity(self.sample_count);
        for i in 0..self.sample_count {
            let at = i * self.layout.record_size
                + self.layout.record_offset
                + self.layout.inval_start
                + byte;
            match self.raw_data.get(at) {
                Some(b) => out.push((b >> bit) & 1 == 0),
                None => out.push(false),
            }
        }
        Some(out)
    }

    /// Returns whether one sample is valid.
    ///
    /// Samples of a channel without an invalidation bit are always valid,
    /// unless the file flags the whole channel invalid.
    pub fn is_valid(&self, index: usize) -> bool {
        if self.channel.all_invalid {
            return false;
        }
        if !self.channel.invalidation_bit || self.layout.inval_bytes == 0 {
            return true;
        }
        let byte = (self.channel.inval_bit_pos / 8) as usize;
        let bit = self.channel.inval_bit_pos % 8;
        if byte >= self.layout.inval_bytes || index >= self.sample_count {
            return true;
        }
        let at = i_offset(&self.layout, index) + byte;
        match self.raw_data.get(at) {
            Some(b) => (b >> bit) & 1 == 0,
            None => false,
        }
    }

    /// Returns the number of valid samples.
    pub fn valid_count(&self) -> usize {
        match self.validity() {
            Some(v) => v.iter().filter(|ok| **ok).count(),
            None => self.sample_count,
        }
    }

    /// Returns the channel name.
    pub fn name(&self) -> &str {
        &self.channel.name
    }

    /// Returns the physical unit.
    pub fn unit(&self) -> &str {
        &self.channel.unit
    }

    /// Returns the number of samples.
    pub fn len(&self) -> usize {
        self.sample_count
    }

    /// Returns true if there are no samples.
    pub fn is_empty(&self) -> bool {
        self.sample_count == 0
    }

    /// Returns the channel metadata.
    pub fn channel(&self) -> &Channel {
        &self.channel
    }

    /// Reads a single raw value at the given sample index.
    fn read_raw_value(&self, index: usize) -> Result<f64> {
        if index >= self.sample_count {
            return Err(Mf4Error::parse_error(format!(
                "Sample index {} out of range (sample count: {})",
                index, self.sample_count
            )));
        }

        // A virtual channel has no bytes in the record: its raw value is the
        // sample's own index, which the conversion then scales.
        if self.channel.channel_type.is_virtual() {
            return Ok(index as f64);
        }

        let record_start = index * self.layout.record_size + self.layout.record_offset;
        let value_start = record_start + self.channel.byte_offset as usize;

        if value_start + self.channel.byte_size() > self.raw_data.len() {
            return Err(Mf4Error::truncated(
                value_start as u64,
                self.channel.byte_size(),
                self.raw_data.len().saturating_sub(value_start),
            ));
        }

        let raw = bytes_to_f64(
            &self.raw_data,
            value_start,
            self.channel.bit_offset,
            self.channel.bit_count,
            self.channel.is_signed(),
            self.channel.is_float(),
            self.channel.is_little_endian(),
        );

        Ok(raw)
    }

    /// Returns the physical value at the given sample index.
    ///
    /// This method reads the raw value and applies the channel conversion.
    pub fn value_at(&self, index: usize) -> Result<f64> {
        let raw = self.read_raw_value(index)?;
        Ok(self.channel.convert(raw))
    }

    /// Whether to skip the strided fast path.
    ///
    /// Always false outside tests; the differential test flips it so the two
    /// decode paths can be compared on the same input.
    #[cfg(not(test))]
    fn force_general_path(&self) -> bool {
        false
    }

    /// See the non-test version.
    #[cfg(test)]
    fn force_general_path(&self) -> bool {
        self.force_general
    }

    /// How a channel's field sits inside a record, when it can be read by
    /// striding rather than by general bit extraction.
    ///
    /// Requires the field to be little-endian and to fit within eight bytes
    /// once its bit offset is included, and every record to be present.
    fn strided_offset(&self) -> Option<StridedField> {
        // A virtual channel's value comes from its index, not from the record,
        // so there is no field to stride over. A well-formed one declines below
        // for having no bits, but a file may still declare a bit count it does
        // not use, and striding that would read another channel's bytes.
        if self.channel.channel_type.is_virtual() {
            return None;
        }

        // Big-endian fields need their bytes reversed, which the strided
        // reader does not do; they take the general path.
        if !self.channel.is_little_endian() {
            return None;
        }

        let bits = self.channel.bit_count;
        let bit_offset = self.channel.bit_offset as u32;
        if bits == 0 || bit_offset + bits > 64 {
            return None;
        }

        // Bytes the field touches, including the ones its bit offset pushes it
        // into.
        let span = (bit_offset + bits).div_ceil(8) as usize;
        let offset = self.layout.record_offset + self.channel.byte_offset as usize;

        // The last record must be complete, or the strided read would run off
        // the end; fall back rather than truncate silently.
        let end = self
            .sample_count
            .checked_sub(1)?
            .checked_mul(self.layout.record_size)?
            .checked_add(offset)?
            .checked_add(span)?;
        if self.sample_count > 0 && end > self.raw_data.len() {
            return None;
        }

        Some(StridedField {
            offset,
            span,
            bit_offset,
            bits,
            aligned: bit_offset == 0 && bits.is_multiple_of(8),
        })
    }

    /// Reads every sample as a strided field.
    ///
    /// Two shapes are handled. A field occupying whole aligned bytes is a
    /// direct copy. A field at a bit offset, or one not a whole number of bytes
    /// — a two-bit bus number or a twenty-nine-bit identifier, which is most of
    /// a bus log — is read as the bytes it touches, then shifted and masked.
    /// Both keep the per-sample work to a fixed sequence over a strided buffer.
    fn decode_strided(&self, kind: ValueKind, field: StridedField) -> Option<SignalValues> {
        let stride = self.layout.record_size;
        let n = self.sample_count;
        if n == 0 || stride < field.span {
            return None;
        }
        let body = self.raw_data.get(field.offset..)?;
        let whole = n.checked_mul(stride).and_then(|len| body.get(..len));

        /// Applies `$f` to each record's field, read as a `u64`.
        macro_rules! map_records {
            ($f:expr) => {{
                let mut out = Vec::with_capacity(n);
                match whole {
                    Some(whole) => {
                        for record in whole.chunks_exact(stride) {
                            out.push($f(field.read(record)?));
                        }
                    }
                    // The final record is short of its full stride but its field
                    // is present; read those individually.
                    None => {
                        for i in 0..n {
                            let at = i * stride;
                            out.push($f(field.read(body.get(at..)?)?));
                        }
                    }
                }
                out
            }};
        }

        /// Sign-extends from the field's width, then narrows.
        macro_rules! signed {
            ($ty:ty) => {{
                let shift = 64 - field.bits;
                map_records!(|v: u64| (((v << shift) as i64) >> shift) as $ty)
            }};
        }

        Some(match kind {
            ValueKind::U8 => SignalValues::U8(map_records!(|v| v as u8)),
            ValueKind::U16 => SignalValues::U16(map_records!(|v| v as u16)),
            ValueKind::U32 => SignalValues::U32(map_records!(|v| v as u32)),
            ValueKind::U64 => SignalValues::U64(map_records!(|v| v)),
            ValueKind::I8 => SignalValues::I8(signed!(i8)),
            ValueKind::I16 => SignalValues::I16(signed!(i16)),
            ValueKind::I32 => SignalValues::I32(signed!(i32)),
            ValueKind::I64 => SignalValues::I64(signed!(i64)),
            ValueKind::F32 => {
                // A float's bits are only a float when whole and aligned.
                if !field.aligned || field.bits != 32 {
                    return None;
                }
                SignalValues::F32(map_records!(|v| f32::from_bits(v as u32)))
            }
            ValueKind::F64 => {
                if !field.aligned || field.bits != 64 || !self.channel.is_float() {
                    return None;
                }
                match &self.channel.conversion {
                    Conversion::None => SignalValues::F64(map_records!(f64::from_bits)),
                    // Linear is overwhelmingly the most common conversion;
                    // specialising it keeps the multiply-add inside the loop
                    // instead of dispatching on the conversion per sample.
                    Conversion::Linear {
                        offset: o,
                        factor: f,
                    } => {
                        let (o, f) = (*o, *f);
                        SignalValues::F64(map_records!(|v| f * f64::from_bits(v) + o))
                    }
                    _ => return None,
                }
            }
            // None of these is a single strided integer field: the CANopen
            // types are records of sub-byte fields and a complex sample is two
            // numbers. All take the general path.
            ValueKind::Bytes
            | ValueKind::Str
            | ValueKind::Complex
            | ValueKind::CanopenDate
            | ValueKind::CanopenTime => return None,
        })
    }

    /// Reads every sample as an unscaled strided field.
    fn decode_strided_raw(&self, kind: ValueKind, field: StridedField) -> Option<SignalValues> {
        let n = self.sample_count;
        // `field.offset` already includes the record offset (see
        // `strided_offset`); adding it again would read every sample one
        // record id late in a sorted group that carries ids.
        let body = self.raw_data.get(field.offset..)?;
        let stride = self.layout.record_size;
        let whole = n.checked_mul(stride).and_then(|len| body.get(..len));

        macro_rules! map_records {
            ($f:expr) => {{
                let mut out = Vec::with_capacity(n);
                match whole {
                    Some(whole) => {
                        for record in whole.chunks_exact(stride) {
                            out.push($f(field.read(record)?));
                        }
                    }
                    None => {
                        for i in 0..n {
                            let at = i * stride;
                            out.push($f(field.read(body.get(at..)?)?));
                        }
                    }
                }
                out
            }};
        }

        macro_rules! signed {
            ($ty:ty) => {{
                let shift = 64 - field.bits;
                map_records!(|v: u64| (((v << shift) as i64) >> shift) as $ty)
            }};
        }

        Some(match kind {
            ValueKind::U8 => SignalValues::U8(map_records!(|v| v as u8)),
            ValueKind::U16 => SignalValues::U16(map_records!(|v| v as u16)),
            ValueKind::U32 => SignalValues::U32(map_records!(|v| v as u32)),
            ValueKind::U64 => SignalValues::U64(map_records!(|v| v)),
            ValueKind::I8 => SignalValues::I8(signed!(i8)),
            ValueKind::I16 => SignalValues::I16(signed!(i16)),
            ValueKind::I32 => SignalValues::I32(signed!(i32)),
            ValueKind::I64 => SignalValues::I64(signed!(i64)),
            ValueKind::F32 => {
                if !field.aligned || field.bits != 32 {
                    return None;
                }
                SignalValues::F32(map_records!(|v| f32::from_bits(v as u32)))
            }
            ValueKind::F64 => {
                if !field.aligned || field.bits != 64 || !self.channel.is_float() {
                    return None;
                }
                SignalValues::F64(map_records!(f64::from_bits))
            }
            _ => return None,
        })
    }

    /// Returns all samples in their raw (unscaled/unconverted) stored type.
    ///
    /// Unlike [`Signal::values`], which applies channel conversions and yields
    /// physical values, this returns the underlying integer, float, string, or byte
    /// samples as recorded in the file.
    pub fn raw_values(&self) -> Result<SignalValues> {
        if let Some(reason) = self.channel.unreadable {
            return Err(Mf4Error::unsupported(
                reason.feature(),
                format!("channel '{}': {}", self.channel.name, reason.detail()),
            ));
        }

        match self.channel.channel_type {
            ChannelType::MaxLength => return self.max_length_values(),
            ChannelType::Sync => {
                return Err(Mf4Error::unsupported(
                    "synchronisation channel",
                    format!(
                        "channel '{}' indexes a media stream rather than carrying samples",
                        self.channel.name
                    ),
                ));
            }
            _ => {}
        }

        if let DataType::Unknown(code) = self.channel.data_type {
            return Err(Mf4Error::unsupported(
                format!("channel data type {code}"),
                format!(
                    "channel '{}' declares a data type this build does not know",
                    self.channel.name
                ),
            ));
        }

        if self.channel.channel_type == ChannelType::VariableLength {
            return self.variable_length_values();
        }

        if let Some(ref elem) = self.channel.array_element {
            if self.channel.array_dynamic_size.is_some() {
                return self.dynamic_array_values(elem);
            }
            if elem.storage == crate::blocks::CaStorage::CgTemplate
                || elem.storage == crate::blocks::CaStorage::DgTemplate
            {
                return self.group_array_values(elem);
            }
            return self.array_values(elem);
        }

        let kind = self.channel.raw_value_kind();
        let n = self.sample_count;

        if !self.force_general_path() {
            if let Some(field) = self.strided_offset() {
                if let Some(values) = self.decode_strided_raw(kind, field) {
                    return Ok(values);
                }
            }
        }

        macro_rules! unsigned {
            ($variant:ident, $ty:ty) => {{
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.raw_uint(i)? as $ty);
                }
                Ok(SignalValues::$variant(out))
            }};
        }
        macro_rules! signed {
            ($variant:ident, $ty:ty) => {{
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.raw_int(i)? as $ty);
                }
                Ok(SignalValues::$variant(out))
            }};
        }

        match kind {
            ValueKind::Complex => self.complex_values(),
            ValueKind::CanopenDate => self.canopen_date_values(),
            ValueKind::CanopenTime => self.canopen_time_values(),
            ValueKind::U8 => unsigned!(U8, u8),
            ValueKind::U16 => unsigned!(U16, u16),
            ValueKind::U32 => unsigned!(U32, u32),
            ValueKind::U64 => unsigned!(U64, u64),
            ValueKind::I8 => signed!(I8, i8),
            ValueKind::I16 => signed!(I16, i16),
            ValueKind::I32 => signed!(I32, i32),
            ValueKind::I64 => signed!(I64, i64),
            ValueKind::F32 => {
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.read_raw_value(i)? as f32);
                }
                Ok(SignalValues::F32(out))
            }
            ValueKind::F64 => {
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.read_raw_value(i)?);
                }
                Ok(SignalValues::F64(out))
            }
            ValueKind::Bytes => {
                let width = self.channel.byte_size();
                if width == 0 {
                    return Err(Mf4Error::parse_error(format!(
                        "channel '{}' declares a zero-byte width, so its samples hold nothing to decode",
                        self.channel.name
                    )));
                }
                let start = self.layout.record_offset + self.channel.byte_offset as usize;
                let stride = self.layout.record_size;
                let total = n.saturating_mul(width);
                if total > self.raw_data.len() {
                    return Err(Mf4Error::truncated(
                        start as u64,
                        total,
                        self.raw_data.len(),
                    ));
                }
                let mut data = vec![0u8; total];
                for (i, slot) in data.chunks_exact_mut(width).enumerate() {
                    let at = start + i * stride;
                    let Some(src) = self.raw_data.get(at..at + width) else {
                        return Err(Mf4Error::truncated(at as u64, width, self.raw_data.len()));
                    };
                    slot.copy_from_slice(src);
                }
                Ok(SignalValues::Bytes { data, width })
            }
            ValueKind::Str => {
                let width = self.channel.byte_size();
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(decode_string(
                        self.sample_bytes(i, width)?,
                        self.channel.data_type,
                    ));
                }
                Ok(SignalValues::Str(out))
            }
        }
    }

    /// Returns all samples in the channel's own type.
    ///
    /// Integer channels stay integers at their natural width, byte-array and
    /// MIME channels stay bytes, and text stays text. Channels carrying a
    /// non-identity conversion decode to [`SignalValues::F64`], since a
    /// conversion produces physical values.
    ///
    /// # Example
    /// ```ignore
    /// match file.signal(&channel)?.values()? {
    ///     SignalValues::U32(ids) => println!("first id: {}", ids[0]),
    ///     SignalValues::Bytes { .. } => println!("opaque payload"),
    ///     other => println!("{} samples of {}", other.len(), other.kind().name()),
    /// }
    /// ```
    pub fn values(&self) -> Result<SignalValues> {
        // A channel this build cannot decode must fail rather than return the
        // part of it that happens to be readable.
        if let Some(reason) = self.channel.unreadable {
            return Err(Mf4Error::unsupported(
                reason.feature(),
                format!("channel '{}': {}", self.channel.name, reason.detail()),
            ));
        }

        // Channel types whose samples are not plain fixed-width values in the
        // record. Left to fall through, each would be decoded as though it were
        // ordinary data: a maximum-length channel's samples vary in length per
        // record, and a synchronisation channel indexes a media stream rather
        // than carrying measurements. Both would yield numbers that look real.
        if self.channel.channel_type == ChannelType::MaxLength {
            return self.max_length_values();
        }

        // A data type this build does not recognise says nothing about how wide
        // the value is, how it is signed, or which way round its bytes go.
        // Falling through would report it as a byte array — a plausible answer
        // to a question the reader cannot answer, which is the B8 failure mode.
        if let DataType::Unknown(code) = self.channel.data_type {
            return Err(Mf4Error::unsupported(
                format!("channel data type {code}"),
                format!(
                    "channel '{}' declares a data type this build does not know",
                    self.channel.name
                ),
            ));
        }

        // A variable-length channel stores an offset into a separate payload
        // stream; the record itself holds no value. A text-keyed conversion
        // still needs those payloads, but as strings rather than as bytes, so
        // it collects them itself below.
        if self.channel.channel_type == ChannelType::VariableLength
            && self.channel.conversion.input() != ConversionInput::Text
        {
            return self.variable_length_values();
        }

        // An array channel stores multiple elements per sample, described by
        // the CA block's template CN. Decode them as flat f64 values — unless
        // the array's size is dynamic, where each sample's real count comes
        // from a companion channel rather than the shape being fixed.
        if let Some(ref elem) = self.channel.array_element {
            if self.channel.array_dynamic_size.is_some() {
                return self.dynamic_array_values(elem);
            }
            if elem.storage == crate::blocks::CaStorage::CgTemplate
                || elem.storage == crate::blocks::CaStorage::DgTemplate
            {
                return self.group_array_values(elem);
            }
            return self.array_values(elem);
        }

        // Conversion types 9 and 10 look their result up by the sample's text,
        // not by a number, so the samples have to be decoded as strings before
        // the conversion can be applied at all.
        if self.channel.conversion.input() == ConversionInput::Text {
            return self.text_keyed_values();
        }

        // A conversion this build cannot evaluate makes every sample of the
        // channel meaningless. Fail rather than fall back to raw values, which
        // would look like plausible measurements.
        if let Conversion::Unsupported { kind, reason } = &self.channel.conversion {
            return Err(Mf4Error::unsupported(
                format!("conversion type {kind:?}"),
                format!("channel '{}': {reason}", self.channel.name),
            ));
        }

        let kind = self.channel.value_kind();
        let n = self.sample_count;

        // Fast path: a channel whose value is a whole number of bytes, aligned
        // to a byte boundary and stored little-endian, is a plain strided read.
        // That covers nearly every channel in practice, and lets the loop become
        // a chunked copy the compiler can vectorise, instead of per-sample bit
        // extraction with a bounds check each time.
        if !self.force_general_path() {
            if let Some(field) = self.strided_offset() {
                if let Some(values) = self.decode_strided(kind, field) {
                    return Ok(values);
                }
            }
        }

        // Text tables map each raw value to a label. A bitfield table renders
        // several labels from one value, so it has its own renderer; the rest
        // are a single lookup.
        if self.channel.conversion.output() == ConversionOutput::Text {
            let bitfield = matches!(self.channel.conversion, Conversion::Bitfield { .. });
            let mut out = Vec::with_capacity(n);
            for i in 0..n {
                let raw = self.read_raw_value(i)?;
                out.push(if bitfield {
                    self.channel
                        .conversion
                        .render_bitfield(raw)
                        .unwrap_or_default()
                } else {
                    self.channel
                        .conversion
                        .convert_text(raw, self.channel.is_float())
                        .unwrap_or_default()
                        .to_string()
                });
            }
            return Ok(SignalValues::Str(out));
        }

        // Integer and float channels share one raw extraction; only the final
        // narrowing differs, so pull the raw words out once per kind.
        macro_rules! unsigned {
            ($variant:ident, $ty:ty) => {{
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.raw_uint(i)? as $ty);
                }
                Ok(SignalValues::$variant(out))
            }};
        }
        macro_rules! signed {
            ($variant:ident, $ty:ty) => {{
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.raw_int(i)? as $ty);
                }
                Ok(SignalValues::$variant(out))
            }};
        }

        match kind {
            ValueKind::Complex => self.complex_values(),
            ValueKind::CanopenDate => self.canopen_date_values(),
            ValueKind::CanopenTime => self.canopen_time_values(),
            ValueKind::U8 => unsigned!(U8, u8),
            ValueKind::U16 => unsigned!(U16, u16),
            ValueKind::U32 => unsigned!(U32, u32),
            ValueKind::U64 => unsigned!(U64, u64),
            ValueKind::I8 => signed!(I8, i8),
            ValueKind::I16 => signed!(I16, i16),
            ValueKind::I32 => signed!(I32, i32),
            ValueKind::I64 => signed!(I64, i64),
            ValueKind::F32 => {
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.read_raw_value(i)? as f32);
                }
                Ok(SignalValues::F32(out))
            }
            ValueKind::F64 => {
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(self.value_at(i)?);
                }
                Ok(SignalValues::F64(out))
            }
            ValueKind::Bytes => {
                // A fixed-width blob — a bus frame, a MIME sample — is a
                // strided copy. Writing into a buffer sized up front turns the
                // loop into one fixed-size move per record, rather than growing
                // a vector and bounds-checking each sample separately.
                let width = self.channel.byte_size();

                // A zero width leaves no bytes to copy and hands
                // `chunks_exact_mut` a chunk size it refuses. A file declaring
                // one — a corrupt `cn_bit_count` — cannot be decoded as a blob
                // at all, so refusing beats panicking.
                if width == 0 {
                    return Err(Mf4Error::parse_error(format!(
                        "channel '{}' declares a zero-byte width, so its samples \
                         hold nothing to decode",
                        self.channel.name
                    )));
                }

                let start = self.layout.record_offset + self.channel.byte_offset as usize;
                let stride = self.layout.record_size;

                // A corrupt sample count saturates the multiply instead of
                // overflowing, then requests a multi-terabyte buffer the
                // process dies trying to back with memory. A record set cannot
                // decode to more bytes than the file holds, so a request past
                // that is a truncated read, not a value.
                let total = n.saturating_mul(width);
                if total > self.raw_data.len() {
                    return Err(Mf4Error::truncated(
                        start as u64,
                        total,
                        self.raw_data.len(),
                    ));
                }

                let mut data = vec![0u8; total];

                for (i, slot) in data.chunks_exact_mut(width).enumerate() {
                    let at = start + i * stride;
                    let Some(src) = self.raw_data.get(at..at + width) else {
                        return Err(Mf4Error::truncated(at as u64, width, self.raw_data.len()));
                    };
                    slot.copy_from_slice(src);
                }
                Ok(SignalValues::Bytes { data, width })
            }
            ValueKind::Str => {
                let width = self.channel.byte_size();
                let mut out = Vec::with_capacity(n);
                for i in 0..n {
                    out.push(decode_string(
                        self.sample_bytes(i, width)?,
                        self.channel.data_type,
                    ));
                }
                Ok(SignalValues::Str(out))
            }
        }
    }

    /// Applies a text-keyed conversion — MF4 type 9 or 10 — to this channel.
    ///
    /// Both look their result up by the sample's own text. A sample matching no
    /// key takes the table's default; a table with no default yields `NaN` for
    /// type 9 and an empty string for type 10, which is what the standard's
    /// "no result" case amounts to.
    fn text_keyed_values(&self) -> Result<SignalValues> {
        let samples = self.text_samples()?;
        let conversion = &self.channel.conversion;

        match conversion {
            Conversion::TextToValue { .. } => Ok(SignalValues::F64(
                samples
                    .iter()
                    .map(|s| conversion.value_for_text(s).unwrap_or(f64::NAN))
                    .collect(),
            )),
            Conversion::TextToText { .. } => Ok(SignalValues::Str(
                samples
                    .into_iter()
                    .map(|s| conversion.text_for_text(&s).unwrap_or_default().to_string())
                    .collect(),
            )),
            // `input()` reports `Text` for exactly the two variants above, so
            // reaching here means the two have drifted apart.
            other => Err(Mf4Error::unsupported(
                format!("text-keyed conversion {other:?}"),
                format!(
                    "channel '{}' is not keyed by text after all",
                    self.channel.name
                ),
            )),
        }
    }

    /// Decodes this channel's samples as strings, from wherever they are stored.
    ///
    /// A text channel is either fixed-width in the record or variable-length in
    /// a payload stream; a text-keyed conversion has to handle both, since
    /// nothing stops a writer from storing its status names either way.
    fn text_samples(&self) -> Result<Vec<String>> {
        let data_type = self.channel.data_type;

        if self.channel.channel_type == ChannelType::VariableLength {
            return match self.variable_length_values()? {
                SignalValues::Bytes { data, width } => Ok(if width == 0 {
                    vec![String::new(); self.sample_count]
                } else {
                    data.chunks_exact(width)
                        .map(|b| decode_string(b, data_type))
                        .collect()
                }),
                SignalValues::VarBytes { data, starts } => Ok(starts
                    .windows(2)
                    .map(|w| decode_string(&data[w[0]..w[1]], data_type))
                    .collect()),
                SignalValues::Str(texts) => Ok(texts),
                other => Err(Mf4Error::unsupported(
                    "text-keyed conversion",
                    format!(
                        "channel '{}' has variable-length payloads decoding to {}, not text",
                        self.channel.name,
                        other.kind()
                    ),
                )),
            };
        }

        let width = self.channel.byte_size();
        let mut out = Vec::with_capacity(self.sample_count);
        for i in 0..self.sample_count {
            out.push(decode_string(self.sample_bytes(i, width)?, data_type));
        }
        Ok(out)
    }

    /// Resolves each record's offset against the channel's payload stream.
    ///
    /// Payloads of a single size come back as [`SignalValues::Bytes`], which is
    /// the common case for bus logs and matches what other readers report;
    /// mixed sizes come back as [`SignalValues::VarBytes`].
    fn variable_length_values(&self) -> Result<SignalValues> {
        let Some(payloads) = &self.payloads else {
            return Err(Mf4Error::unsupported(
                "variable-length signal data (VLSD)",
                format!("channel '{}' has no payloads attached", self.channel.name),
            ));
        };

        let n = self.sample_count;
        let offsets = self.vlsd_offsets()?;

        // A variable-length channel declaring a string data type carries text,
        // and the payload is the string itself. Reporting it as bytes would
        // leave the channel's own declared encoding for the caller to reapply,
        // and a sample whose length happens to match its neighbours' would be
        // indistinguishable from a fixed-width blob.
        if self.channel.data_type.is_string() {
            let mut out = Vec::with_capacity(n);
            let mut hint = 0usize;
            for &offset in &offsets {
                // A missing payload means the file is inconsistent, which is
                // represented as an empty sample rather than failing the
                // channel — the same choice the byte paths below make.
                match payloads.get_from(offset, hint) {
                    Some((payload, at)) => {
                        out.push(decode_string(payload, self.channel.data_type));
                        hint = at + 1;
                    }
                    None => out.push(String::new()),
                }
            }
            return Ok(SignalValues::Str(out));
        }

        // When every payload is the same size — which a bus log almost always
        // is — the output is a plain fixed-width buffer. Filling it directly
        // avoids both the per-sample offset table and growing the buffer a
        // payload at a time.
        if let Some(width) = payloads.uniform_len() {
            // The fixed-width path copies one existing payload per slot, so it
            // is only usable while the whole decode provably fits inside the
            // payload stream — the window `payloads.total_bytes()` describes.
            // A stream that serves fewer bytes than the channel declares — an
            // entirely empty one, or an offset pointing nowhere, or a stray
            // sample count that would ask for a buffer the process cannot
            // allocate — is not an error: this reader already renders a
            // payload-less sample as an empty one, the same choice the string
            // branch above makes. Such channels fall through to the
            // variable-size path below, whose zero-width shapes cannot panic.
            let total = n.saturating_mul(width);
            if width > 0 && total <= payloads.total_bytes() {
                let mut data = vec![0u8; total];
                let mut hint = 0usize;
                let mut all_resolved = true;

                for (slot, &offset) in data.chunks_exact_mut(width).zip(offsets.iter()) {
                    match payloads.get_from(offset, hint) {
                        Some((payload, at)) if payload.len() == width => {
                            slot.copy_from_slice(payload);
                            hint = at + 1;
                        }
                        _ => {
                            all_resolved = false;
                            break;
                        }
                    }
                }

                // A fixed-width buffer cannot express "this sample has no
                // payload": leaving the slot zeroed would report bytes the file
                // never contained. If any offset failed to resolve, fall through
                // to the variable-width path, where a missing payload is
                // genuinely empty.
                if all_resolved {
                    return Ok(SignalValues::Bytes { data, width });
                }
            }
        }

        // Mixed sizes: track where each sample begins. Size the output from the
        // payload stream, so growing it does not dominate; the exact total would
        // mean resolving every offset twice.
        let mut data = Vec::with_capacity(payloads.total_bytes());
        let mut starts = Vec::with_capacity(n + 1);

        // Records reference payloads in the order they were written, so carry
        // the last position forward as a hint rather than searching the whole
        // table for every sample.
        let mut hint = 0usize;
        for &offset in &offsets {
            starts.push(data.len());
            // A missing payload means the file is inconsistent, which is
            // represented as an empty sample rather than failing the channel.
            if let Some((payload, at)) = payloads.get_from(offset, hint) {
                data.extend_from_slice(payload);
                hint = at + 1;
            }
        }
        starts.push(data.len());

        // Uniform lengths collapse to a fixed width.
        let uniform = starts
            .windows(2)
            .map(|w| w[1] - w[0])
            .try_fold(None::<usize>, |acc, len| match acc {
                None => Some(Some(len)),
                Some(first) if first == len => Some(Some(first)),
                Some(_) => None,
            })
            .flatten();

        match uniform {
            Some(width) if n > 0 && width > 0 => Ok(SignalValues::Bytes { data, width }),
            _ => Ok(SignalValues::VarBytes { data, starts }),
        }
    }

    /// Decodes a maximum-length channel — MF4 `cn_type` 5.
    ///
    /// The data sits in the record, sized to the longest sample the channel
    /// will ever carry, and the bytes actually used per sample are counted by a
    /// separate channel of the same group that `cn_data` names. So unlike VLSD
    /// there is no payload block to resolve: both halves are in the record, and
    /// what is needed is the other channel's field.
    ///
    /// The result is [`SignalValues::VarBytes`] even when every sample happens
    /// to be the same length. A channel declared as maximum-length is saying
    /// its samples vary, and reporting a fixed width would erase the
    /// distinction between "eight bytes used" and "eight bytes available".
    fn max_length_values(&self) -> Result<SignalValues> {
        let Some(length) = self.mlsd_length else {
            return Err(Mf4Error::unsupported(
                "maximum-length signal data (MLSD)",
                format!(
                    "channel '{}' names no channel holding its sample lengths, \
                     so its data cannot be bounded",
                    self.channel.name
                ),
            ));
        };

        let max = self.channel.byte_size();
        let mut data = Vec::with_capacity(self.sample_count.saturating_mul(max));
        let mut starts = Vec::with_capacity(self.sample_count + 1);

        for i in 0..self.sample_count {
            starts.push(data.len());

            let at = i * self.layout.record_size
                + self.layout.record_offset
                + length.byte_offset as usize;
            let used = read_uint(
                &self.raw_data,
                at,
                length.bit_offset,
                length.bit_count,
                length.little_endian,
            ) as usize;

            // A count past the declared maximum would take bytes belonging to
            // the next channel. That is the file contradicting itself, and
            // clamping would quietly hand back those bytes as measurement data.
            if used > max {
                return Err(Mf4Error::parse_error(format!(
                    "channel '{}' sample {i} declares {used} bytes, more than the \
                     {max} its maximum length allows",
                    self.channel.name
                )));
            }

            data.extend_from_slice(&self.sample_bytes(i, max)?[..used]);
        }
        starts.push(data.len());

        Ok(SignalValues::VarBytes { data, starts })
    }

    /// Decodes a complex channel into parallel real and imaginary parts.
    ///
    /// A complex sample is two floats laid end to end, so `cn_bit_count` covers
    /// the pair: 64 bits means two `f32`, 128 bits two `f64`. Any other width
    /// is not a complex number this build can read, and is refused rather than
    /// guessed at.
    fn complex_values(&self) -> Result<SignalValues> {
        let bits = self.channel.bit_count;
        let part = match bits {
            64 => 4usize,
            128 => 8usize,
            other => {
                return Err(Mf4Error::unsupported(
                    "complex channel",
                    format!(
                        "channel '{}' declares {other} bits; a complex sample is \
                         two floats, so 64 or 128",
                        self.channel.name
                    ),
                ));
            }
        };

        let le = self.channel.is_little_endian();
        let mut re = Vec::with_capacity(self.sample_count);
        let mut im = Vec::with_capacity(self.sample_count);

        for i in 0..self.sample_count {
            let s = self.sample_bytes(i, part * 2)?;
            if part == 4 {
                re.push(read_f32(s, 0, le) as f64);
                im.push(read_f32(s, part, le) as f64);
            } else {
                re.push(read_f64(s, 0, le));
                im.push(read_f64(s, part, le));
            }
        }
        Ok(SignalValues::Complex { re, im })
    }

    /// Decodes a CANopen date channel — MF4 data type 12, seven bytes.
    ///
    /// The layout is the CiA 301 date record the MF4 standard refers to. Every
    /// field but the milliseconds shares a byte with reserved bits, so each is
    /// masked to its own width: reading a byte whole would fold a neighbouring
    /// flag into the value.
    ///
    /// ```text
    /// byte 0-1  ms within the minute, u16 little-endian (0..59999)
    /// byte 2    bits 0-5   minutes
    /// byte 3    bits 0-4   hours          bit 7  summer time
    /// byte 4    bits 0-4   day of month   bits 5-7  day of week (1=Monday)
    /// byte 5    bits 0-5   month
    /// byte 6    bits 0-6   years since 1984
    /// ```
    fn canopen_date_values(&self) -> Result<SignalValues> {
        let mut out = Vec::with_capacity(self.sample_count);
        for i in 0..self.sample_count {
            let b = self.sample_bytes(i, 7)?;
            out.push(CanopenDate {
                ms: u16::from_le_bytes([b[0], b[1]]),
                minute: b[2] & 0x3F,
                hour: b[3] & 0x1F,
                summer_time: b[3] & 0x80 != 0,
                day: b[4] & 0x1F,
                day_of_week: b[4] >> 5,
                month: b[5] & 0x3F,
                year: 1984 + (b[6] & 0x7F) as u16,
            });
        }
        Ok(SignalValues::CanopenDate(out))
    }

    /// Decodes a CANopen time channel — MF4 data type 13, six bytes.
    ///
    /// ```text
    /// byte 0-3  bits 0-27  milliseconds since midnight (u32 little-endian)
    /// byte 4-5  days since 1984-01-01 (u16 little-endian)
    /// ```
    ///
    /// The upper four bits of the first field are reserved, so the value is
    /// masked to 28 bits rather than taken as a whole `u32`.
    fn canopen_time_values(&self) -> Result<SignalValues> {
        let mut out = Vec::with_capacity(self.sample_count);
        for i in 0..self.sample_count {
            let b = self.sample_bytes(i, 6)?;
            out.push(CanopenTime {
                ms_since_midnight: u32::from_le_bytes([b[0], b[1], b[2], b[3]]) & 0x0FFF_FFFF,
                days_since_1984: u16::from_le_bytes([b[4], b[5]]),
            });
        }
        Ok(SignalValues::CanopenTime(out))
    }

    /// Decodes one array element from `raw_data` at `offset` to `f64`.
    fn read_array_element(&self, elem: &crate::model::ArrayElement, offset: usize) -> f64 {
        read_element_from_bytes(
            &self.raw_data,
            elem,
            offset,
            &self.channel.conversion,
            self.channel.is_float(),
        )
    }

    /// Decodes a CG- or DG-template array channel's elements by gathering values
    /// across separate member channel groups or data groups.
    fn group_array_values(&self, elem: &crate::model::ArrayElement) -> Result<SignalValues> {
        let Some(members) = &self.array_group_members else {
            return Err(Mf4Error::unsupported(
                "channel array (CA)",
                format!(
                    "channel '{}': member group records not attached",
                    self.channel.name
                ),
            ));
        };

        let elements_per_sample = self
            .channel
            .array_shape
            .as_ref()
            .map(|s| s.iter().copied().fold(1u64, |acc, d| acc.saturating_mul(d)) as usize)
            .unwrap_or(0);

        if elements_per_sample == 0 || members.is_empty() {
            return Ok(SignalValues::Array {
                values: Vec::new(),
                elements_per_sample: 0,
            });
        }

        if members.len() != elements_per_sample {
            return Err(Mf4Error::parse_error(format!(
                "channel '{}' declares {} array elements per sample, but CA block has {} member groups",
                self.channel.name, elements_per_sample, members.len()
            )));
        }

        let n = members[0].sample_count;
        for (k, m) in members.iter().enumerate() {
            if m.sample_count != n {
                return Err(Mf4Error::parse_error(format!(
                    "channel '{}' member group {} has {} samples, which disagrees with sibling count {}",
                    self.channel.name, k, m.sample_count, n
                )));
            }
        }

        let shape = self.channel.array_shape.as_deref().unwrap_or(&[]);
        let order: Option<Vec<usize>> = (elem.inverse_layout && shape.len() > 1)
            .then(|| row_major_to_stored(shape, elements_per_sample));

        let total = n.saturating_mul(elements_per_sample);
        let mut values = Vec::with_capacity(total);

        for i in 0..n {
            for j in 0..elements_per_sample {
                let k = order.as_ref().map_or(j, |o| o[j]);
                let member = &members[k];
                let offset = i * member.layout.record_size
                    + member.layout.record_offset
                    + elem.byte_offset as usize;
                values.push(read_element_from_bytes(
                    &member.raw_data,
                    elem,
                    offset,
                    &self.channel.conversion,
                    self.channel.is_float(),
                ));
            }
        }

        Ok(SignalValues::Array {
            values,
            elements_per_sample,
        })
    }

    /// Decodes an array channel's elements as flat f64 values.
    ///
    /// Each sample holds `elements_per_sample` values stored contiguously
    /// starting at the parent channel's byte offset. The template CN block
    /// (stored in [`Channel::array_element`]) gives each element's data type,
    /// bit width and bit offset.
    fn array_values(&self, elem: &crate::model::ArrayElement) -> Result<SignalValues> {
        let elements_per_sample = self
            .channel
            .array_shape
            .as_ref()
            .map(|s| s.iter().copied().fold(1u64, |acc, d| acc.saturating_mul(d)) as usize)
            .unwrap_or(0);

        if elements_per_sample == 0 {
            return Ok(SignalValues::Array {
                values: Vec::new(),
                elements_per_sample: 0,
            });
        }

        // The parent channel's byte offset within the record, plus the
        // template element's own offset, gives the first element's position.
        let base = self.layout.record_offset
            + self.channel.byte_offset as usize
            + elem.byte_offset as usize;

        // A shape claiming more elements than fit between `base` and the end
        // of the record is malformed: `ca_dim_size` is file-supplied, and one
        // flipped byte can turn a handful of real elements into billions. The
        // record itself is proof of how many can possibly be real, so that
        // bound is checked before anything is allocated on the strength of
        // the declared shape alone.
        //
        // A look-up array composed with another CA block (B30) has no single
        // flat stride — each nesting level has its own — so `element_offsets`
        // carries every element's byte offset directly, and the bound is the
        // highest of those actually touching the record, not a stride-derived
        // maximum.
        let elem_width = (elem.bit_count as usize).div_ceil(8).max(1);
        if let Some(offsets) = &elem.element_offsets {
            let touched = offsets
                .iter()
                .copied()
                .max()
                .unwrap_or(0)
                .saturating_add(base)
                .saturating_add(elem_width);
            if touched > self.layout.record_size {
                return Err(Mf4Error::parse_error(format!(
                    "channel '{}' declares {} array elements per sample, but the furthest \
                     touches byte {} of its {}-byte record",
                    self.channel.name, elements_per_sample, touched, self.layout.record_size,
                )));
            }
        } else {
            let elem_stride = elem.stride.max(1);
            let max_elements = self
                .layout
                .record_size
                .saturating_sub(base)
                .div_ceil(elem_stride);
            if elements_per_sample > max_elements {
                return Err(Mf4Error::parse_error(format!(
                    "channel '{}' declares {} array elements per sample, but its \
                     {}-byte record can hold at most {} at a stride of {} bytes",
                    self.channel.name,
                    elements_per_sample,
                    self.layout.record_size,
                    max_elements,
                    elem_stride,
                )));
            }
        }

        let n = self.sample_count;
        let total = n.saturating_mul(elements_per_sample);
        let mut values = Vec::with_capacity(total);

        let stride = self.layout.record_size;

        // With inverse layout the first dimension varies fastest in the
        // record, so the stored order is the transpose of the row-major order
        // this returns. Build the permutation once rather than per sample.
        // Not used for a chain-composed array: `element_offsets` already
        // carries every level's own orientation.
        let shape = self.channel.array_shape.as_deref().unwrap_or(&[]);
        let order: Option<Vec<usize>> =
            (elem.element_offsets.is_none() && elem.inverse_layout && shape.len() > 1)
                .then(|| row_major_to_stored(shape, elements_per_sample));

        for i in 0..n {
            let record_start = i * stride + base;
            for j in 0..elements_per_sample {
                let offset = match &elem.element_offsets {
                    Some(offsets) => record_start + offsets[j],
                    None => {
                        let j = order.as_ref().map_or(j, |o| o[j]);
                        record_start + j * elem.stride.max(1)
                    }
                };
                values.push(self.read_array_element(elem, offset));
            }
        }

        Ok(SignalValues::Array {
            values,
            elements_per_sample,
        })
    }

    /// Decodes a dynamic-size array channel's elements.
    ///
    /// `ca_dim_size` is only the largest shape any sample may take; the real
    /// count for each sample comes from `self.dynamic_array_length`, read
    /// exactly like a maximum-length channel's byte count (see
    /// [`Signal::max_length_values`]) — both are "the field is sized for the
    /// worst case, and another channel of the same record says how much of it
    /// this sample actually used."
    fn dynamic_array_values(&self, elem: &crate::model::ArrayElement) -> Result<SignalValues> {
        let Some(length) = self.dynamic_array_length else {
            return Err(Mf4Error::unsupported(
                "dynamic-size array",
                format!(
                    "channel '{}' names a dimension whose real size lives outside this \
                     record, so it cannot be resolved",
                    self.channel.name
                ),
            ));
        };

        let max = self
            .channel
            .array_shape
            .as_ref()
            .map(|s| s.iter().copied().fold(1u64, |acc, d| acc.saturating_mul(d)) as usize)
            .unwrap_or(0);

        let n = self.sample_count;
        if max == 0 {
            return Ok(SignalValues::ArrayVarLen {
                values: Vec::new(),
                starts: vec![0; n + 1],
            });
        }

        // The same structural bound as a fixed-size array: the declared
        // maximum has to fit between the array's base and the end of the
        // record, checked once up front rather than per sample.
        let base = self.layout.record_offset
            + self.channel.byte_offset as usize
            + elem.byte_offset as usize;
        let elem_stride = elem.stride.max(1);
        let max_elements = self
            .layout
            .record_size
            .saturating_sub(base)
            .div_ceil(elem_stride);
        if max > max_elements {
            return Err(Mf4Error::parse_error(format!(
                "channel '{}' declares a maximum of {} array elements per sample, but its \
                 {}-byte record can hold at most {} at a stride of {} bytes",
                self.channel.name, max, self.layout.record_size, max_elements, elem_stride,
            )));
        }

        let stride = self.layout.record_size;
        let mut values = Vec::new();
        let mut starts = Vec::with_capacity(n + 1);

        for i in 0..n {
            starts.push(values.len());
            let record_start = i * stride + base;

            let length_at = i * stride + self.layout.record_offset + length.byte_offset as usize;
            let used = read_uint(
                &self.raw_data,
                length_at,
                length.bit_offset,
                length.bit_count,
                length.little_endian,
            ) as usize;

            // A count past the declared maximum would take bytes belonging to
            // whatever follows in the record — the same contradiction
            // `max_length_values` refuses rather than clamps.
            if used > max {
                return Err(Mf4Error::parse_error(format!(
                    "channel '{}' sample {i} declares {used} array elements, more than the \
                     {max} its maximum size allows",
                    self.channel.name
                )));
            }

            for j in 0..used {
                let offset = record_start + j * elem_stride;
                values.push(self.read_array_element(elem, offset));
            }
        }
        starts.push(values.len());

        Ok(SignalValues::ArrayVarLen { values, starts })
    }

    /// Reads every record's payload offset.
    ///
    /// The offsets are byte-aligned 64-bit fields, so they can be read by
    /// striding even though the channel's own data type is not a little-endian
    /// numeric one — see [`Signal::vlsd_offset`] for why the channel's
    /// endianness does not apply here.
    pub(crate) fn vlsd_offsets(&self) -> Result<Vec<u64>> {
        let n = self.sample_count;
        let bits = self.channel.bit_count;
        let bit_offset = self.channel.bit_offset as u32;

        if bit_offset == 0 && bits.is_multiple_of(8) && bits <= 64 && n > 0 {
            let field = StridedField {
                offset: self.layout.record_offset + self.channel.byte_offset as usize,
                span: (bits / 8) as usize,
                bit_offset: 0,
                bits,
                aligned: true,
            };
            let stride = self.layout.record_size;
            if stride >= field.span {
                if let Some(body) = self.raw_data.get(field.offset..) {
                    if let Some(whole) = n.checked_mul(stride).and_then(|len| body.get(..len)) {
                        let mut out = Vec::with_capacity(n);
                        for record in whole.chunks_exact(stride) {
                            match field.read(record) {
                                Some(v) => out.push(v),
                                None => break,
                            }
                        }
                        if out.len() == n {
                            return Ok(out);
                        }
                    }
                }
            }
        }

        (0..n).map(|i| self.vlsd_offset(i)).collect()
    }

    /// Reads the payload offset a variable-length record carries.
    ///
    /// The offset is a plain little-endian integer, independent of the
    /// channel's declared data type: a variable-length channel's type describes
    /// its *payload* — `MimeSample` for a bus frame, say — which says nothing
    /// about the byte order of the offset pointing at it. Reading it through the
    /// channel's endianness gives a byte-reversed offset that resolves to
    /// nothing.
    fn vlsd_offset(&self, index: usize) -> Result<u64> {
        self.bounds_check(index)?;
        Ok(read_uint(
            &self.raw_data,
            self.value_offset(index),
            self.channel.bit_offset,
            self.channel.bit_count,
            true,
        ))
    }

    /// Returns the raw bytes of one sample.
    fn sample_bytes(&self, index: usize, width: usize) -> Result<&[u8]> {
        let start = self.value_offset(index);
        self.raw_data
            .get(start..start + width)
            .ok_or_else(|| Mf4Error::truncated(start as u64, width, self.raw_data.len()))
    }

    /// Byte offset of a sample's value within the raw record buffer.
    fn value_offset(&self, index: usize) -> usize {
        index * self.layout.record_size
            + self.layout.record_offset
            + self.channel.byte_offset as usize
    }

    /// Extracts one sample's raw bit field as an unsigned integer.
    fn raw_uint(&self, index: usize) -> Result<u64> {
        if self.channel.channel_type.is_virtual() {
            self.index_check(index)?;
            return Ok(index as u64);
        }
        self.bounds_check(index)?;
        Ok(read_uint(
            &self.raw_data,
            self.value_offset(index),
            self.channel.bit_offset,
            self.channel.bit_count,
            self.channel.is_little_endian(),
        ))
    }

    /// Extracts one sample's raw bit field as a sign-extended integer.
    fn raw_int(&self, index: usize) -> Result<i64> {
        if self.channel.channel_type.is_virtual() {
            self.index_check(index)?;
            return Ok(index as i64);
        }
        self.bounds_check(index)?;
        Ok(read_int(
            &self.raw_data,
            self.value_offset(index),
            self.channel.bit_offset,
            self.channel.bit_count,
            self.channel.is_little_endian(),
        ))
    }

    /// Fails if `index` is past the last sample.
    ///
    /// Separate from [`Signal::bounds_check`] because a virtual channel has no
    /// bytes to check: only its index has to be in range.
    fn index_check(&self, index: usize) -> Result<()> {
        if index >= self.sample_count {
            return Err(Mf4Error::parse_error(format!(
                "Sample index {} out of range (sample count: {})",
                index, self.sample_count
            )));
        }
        Ok(())
    }

    /// Fails if `index` is past the end, or if the sample's bytes are not present.
    fn bounds_check(&self, index: usize) -> Result<()> {
        self.index_check(index)?;
        let start = self.value_offset(index);
        let end = start + self.channel.byte_size();
        if end > self.raw_data.len() {
            return Err(Mf4Error::truncated(
                start as u64,
                self.channel.byte_size(),
                self.raw_data.len().saturating_sub(start),
            ));
        }
        Ok(())
    }

    /// Returns all physical values as a vector of f64.
    ///
    /// A uniform numeric view over any channel. This is lossy where the channel
    /// is not naturally an `f64`: integers beyond 2^53 lose precision, and
    /// byte-array or text channels yield `NaN`, since they have no numeric
    /// meaning. Use [`Signal::values`] to get samples in their own type.
    pub fn values_f64(&self) -> Result<Vec<f64>> {
        match self.values()? {
            // Already the right type: hand it over instead of copying it.
            SignalValues::F64(v) => Ok(v),
            other => Ok(other.to_f64()),
        }
    }

    /// Returns an iterator over physical values.
    ///
    /// This is more memory-efficient than `values_f64()` for large signals
    /// as it decodes values on demand.
    pub fn iter(&self) -> SignalIterator<'_> {
        SignalIterator {
            signal: self,
            index: 0,
        }
    }

    /// Returns the minimum and maximum physical values.
    ///
    /// This scans all samples to find the actual min/max.
    pub fn min_max(&self) -> Result<(f64, f64)> {
        if self.sample_count == 0 {
            return Err(Mf4Error::parse_error(
                "Cannot compute min/max of empty signal",
            ));
        }

        let mut min = f64::MAX;
        let mut max = f64::MIN;

        for i in 0..self.sample_count {
            let value = self.value_at(i)?;
            if value < min {
                min = value;
            }
            if value > max {
                max = value;
            }
        }

        Ok((min, max))
    }

    /// Returns the mean (average) physical value.
    pub fn mean(&self) -> Result<f64> {
        if self.sample_count == 0 {
            return Err(Mf4Error::parse_error("Cannot compute mean of empty signal"));
        }

        let sum: f64 = self.iter().sum::<Result<f64>>()?;
        Ok(sum / self.sample_count as f64)
    }
}

impl std::fmt::Debug for Signal {
    /// Summarises the signal rather than dumping its samples, which can number
    /// in the millions.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Signal")
            .field("channel", &self.channel.name)
            .field("unit", &self.channel.unit)
            .field("kind", &self.channel.value_kind().name())
            .field("samples", &self.sample_count)
            .field("record_size", &self.layout.record_size)
            .finish()
    }
}

/// Iterator over signal values.
pub struct SignalIterator<'a> {
    signal: &'a Signal,
    index: usize,
}

impl<'a> Iterator for SignalIterator<'a> {
    type Item = Result<f64>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.signal.sample_count {
            return None;
        }
        let value = self.signal.value_at(self.index);
        self.index += 1;
        Some(value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.signal.sample_count - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a> ExactSizeIterator for SignalIterator<'a> {}

/// A pair of time and value signals for time-series data.
pub struct TimeSeries {
    /// Time/master channel signal.
    pub time: Signal,
    /// Value channel signal.
    pub values: Signal,
}

impl TimeSeries {
    /// Creates a new time series from time and value signals.
    pub fn new(time: Signal, values: Signal) -> Result<Self> {
        if time.len() != values.len() {
            return Err(Mf4Error::parse_error(format!(
                "Time and value signal lengths don't match: {} vs {}",
                time.len(),
                values.len()
            )));
        }
        Ok(TimeSeries { time, values })
    }

    /// Returns the number of samples.
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Returns true if there are no samples.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Returns an iterator over (time, value) pairs.
    pub fn iter(&self) -> TimeSeriesIterator<'_> {
        TimeSeriesIterator {
            time_iter: self.time.iter(),
            value_iter: self.values.iter(),
        }
    }

    /// Returns all data as vectors of (timestamps, values).
    pub fn to_vectors(&self) -> Result<(Vec<f64>, Vec<f64>)> {
        let timestamps = self.time.values_f64()?;
        let values = self.values.values_f64()?;
        Ok((timestamps, values))
    }
}

/// Iterator over time series (time, value) pairs.
pub struct TimeSeriesIterator<'a> {
    time_iter: SignalIterator<'a>,
    value_iter: SignalIterator<'a>,
}

impl<'a> Iterator for TimeSeriesIterator<'a> {
    type Item = Result<(f64, f64)>;

    fn next(&mut self) -> Option<Self::Item> {
        match (self.time_iter.next(), self.value_iter.next()) {
            (Some(Ok(t)), Some(Ok(v))) => Some(Ok((t, v))),
            (Some(Err(e)), _) | (_, Some(Err(e))) => Some(Err(e)),
            _ => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.value_iter.size_hint()
    }
}

impl<'a> ExactSizeIterator for TimeSeriesIterator<'a> {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::blocks::{ChannelType, Conversion, DataType, SyncType};

    /// A plain layout: fixed stride, no record ID, no invalidation bytes.
    fn plain(record_size: usize) -> RecordLayout {
        RecordLayout {
            record_size,
            record_offset: 0,
            inval_start: record_size,
            inval_bytes: 0,
        }
    }

    fn create_test_channel() -> Channel {
        Channel {
            id: 0,
            index: 0,
            channel_group_index: 0,
            data_group_index: 0,
            name: "TestChannel".to_string(),
            unit: "V".to_string(),
            channel_type: ChannelType::FixedLength,
            sync_type: SyncType::None,
            data_type: DataType::FloatLe,
            conversion: Conversion::Linear {
                offset: 0.0,
                factor: 1.0,
            },
            bit_count: 32,
            byte_offset: 0,
            bit_offset: 0,
            all_invalid: false,
            invalidation_bit: false,
            inval_bit_pos: 0,
            comment: String::new(),
            source: None,
            min_value: None,
            max_value: None,
            sample_count: 0,
            cn_offset: 0,
            data_link: 0,
            unreadable: None,
            array_shape: None,
            array_element: None,
            array_dynamic_size: None,
        }
    }

    #[test]
    fn test_signal_basic() {
        // Create raw data: 3 x f32 values [1.0, 2.0, 3.0]
        let mut raw_data = Vec::new();
        raw_data.extend_from_slice(&1.0f32.to_le_bytes());
        raw_data.extend_from_slice(&2.0f32.to_le_bytes());
        raw_data.extend_from_slice(&3.0f32.to_le_bytes());

        let channel = create_test_channel();
        let signal = Signal::new(channel, Arc::new(raw_data), plain(4), 3);

        assert_eq!(signal.len(), 3);
        assert_eq!(signal.name(), "TestChannel");
        assert_eq!(signal.unit(), "V");
    }

    #[test]
    fn an_out_of_range_read_reports_the_count_itself_not_count_minus_one() {
        // A group with no records yields a signal with `sample_count == 0`.
        // The out-of-range error once formatted `sample_count - 1`, which
        // underflowed on exactly this shape.
        let channel = create_test_channel();
        let signal = Signal::new(channel, Arc::new(Vec::new()), plain(4), 0);

        let err = signal.value_at(0).unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains("(sample count: 0)"),
            "the error must name the sample count, got: {message}"
        );
    }

    #[test]
    fn test_signal_values() {
        let mut raw_data = Vec::new();
        raw_data.extend_from_slice(&1.0f32.to_le_bytes());
        raw_data.extend_from_slice(&2.0f32.to_le_bytes());
        raw_data.extend_from_slice(&3.0f32.to_le_bytes());

        let channel = create_test_channel();
        let signal = Signal::new(channel, Arc::new(raw_data), plain(4), 3);

        let values = signal.values_f64().unwrap();
        assert_eq!(values.len(), 3);
        assert!((values[0] - 1.0).abs() < 0.001);
        assert!((values[1] - 2.0).abs() < 0.001);
        assert!((values[2] - 3.0).abs() < 0.001);
    }

    #[test]
    fn test_signal_with_conversion() {
        let mut raw_data = Vec::new();
        raw_data.extend_from_slice(&10.0f32.to_le_bytes());

        let mut channel = create_test_channel();
        channel.conversion = Conversion::Linear {
            offset: 5.0,
            factor: 2.0,
        };

        let signal = Signal::new(channel, Arc::new(raw_data), plain(4), 1);
        let value = signal.value_at(0).unwrap();

        // 2.0 * 10.0 + 5.0 = 25.0
        assert!((value - 25.0).abs() < 0.001);
    }

    #[test]
    fn test_signal_iterator() {
        let mut raw_data = Vec::new();
        for i in 0..5 {
            raw_data.extend_from_slice(&(i as f32).to_le_bytes());
        }

        let channel = create_test_channel();
        let signal = Signal::new(channel, Arc::new(raw_data), plain(4), 5);

        let values: Vec<f64> = signal.iter().map(|r| r.unwrap()).collect();
        assert_eq!(values.len(), 5);
        for (i, &v) in values.iter().enumerate() {
            assert!((v - i as f64).abs() < 0.001);
        }
    }

    #[test]
    fn test_signal_min_max() {
        let mut raw_data = Vec::new();
        raw_data.extend_from_slice(&(-5.0f32).to_le_bytes());
        raw_data.extend_from_slice(&3.0f32.to_le_bytes());
        raw_data.extend_from_slice(&10.0f32.to_le_bytes());

        let channel = create_test_channel();
        let signal = Signal::new(channel, Arc::new(raw_data), plain(4), 3);

        let (min, max) = signal.min_max().unwrap();
        assert!((min - (-5.0)).abs() < 0.001);
        assert!((max - 10.0).abs() < 0.001);
    }

    #[test]
    fn mean_propagates_a_truncated_sample_error() {
        let raw = Arc::new(6.0f32.to_le_bytes().to_vec());
        let complete = Signal::new(create_test_channel(), raw.clone(), plain(4), 1);
        assert_eq!(complete.mean().unwrap(), 6.0);
        let truncated = Signal::new(create_test_channel(), raw, plain(4), 2);
        assert!(truncated.value_at(1).is_err());
        assert!(truncated.mean().is_err());
    }
    /// Builds a signal whose records are `[u8 value][inval byte]`, with the
    /// channel's invalidation bit at `bit_pos`.
    fn signal_with_invalidation(values: &[u8], inval: &[u8], bit_pos: u32) -> Signal {
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 8;
        ch.byte_offset = 0;
        ch.conversion = Conversion::None;
        ch.invalidation_bit = true;
        ch.inval_bit_pos = bit_pos;

        let mut raw = Vec::new();
        for (v, i) in values.iter().zip(inval) {
            raw.push(*v);
            raw.push(*i);
        }
        Signal::new(
            ch,
            Arc::new(raw),
            RecordLayout {
                record_size: 2,
                record_offset: 0,
                inval_start: 1,
                inval_bytes: 1,
            },
            values.len(),
        )
    }

    #[test]
    fn a_set_invalidation_bit_marks_a_sample_invalid() {
        // Bit 0 set on the middle sample.
        let sig =
            signal_with_invalidation(&[10, 20, 30], &[0b0000_0000, 0b0000_0001, 0b0000_0000], 0);
        assert_eq!(sig.validity(), Some(vec![true, false, true]));
        assert!(sig.is_valid(0));
        assert!(!sig.is_valid(1));
        assert!(sig.is_valid(2));
        assert_eq!(sig.valid_count(), 2);
    }

    #[test]
    fn reads_the_invalidation_bit_at_its_declared_position() {
        // Bit 5 is this channel's; bit 0 belongs to some other channel and must
        // not be mistaken for it.
        let sig = signal_with_invalidation(&[1, 2], &[0b0000_0001, 0b0010_0000], 5);
        assert_eq!(sig.validity(), Some(vec![true, false]));
    }

    #[test]
    fn invalidation_bits_can_span_several_bytes() {
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 8;
        ch.conversion = Conversion::None;
        ch.invalidation_bit = true;
        ch.inval_bit_pos = 9; // second invalidation byte, bit 1

        // record = [value][inval0][inval1]
        let raw = vec![1, 0, 0b0000_0010, 2, 0, 0b0000_0000];
        let sig = Signal::new(
            ch,
            Arc::new(raw),
            RecordLayout {
                record_size: 3,
                record_offset: 0,
                inval_start: 1,
                inval_bytes: 2,
            },
            2,
        );
        assert_eq!(sig.validity(), Some(vec![false, true]));
    }

    #[test]
    fn a_channel_without_an_invalidation_bit_reports_no_validity_info() {
        let sig = Signal::new(create_test_channel(), Arc::new(vec![0; 12]), plain(4), 3);
        assert_eq!(sig.validity(), None);
        assert!(sig.is_valid(0));
        assert_eq!(sig.valid_count(), 3, "all samples count as valid");
    }

    #[test]
    fn a_bit_position_outside_the_invalidation_area_is_not_treated_as_valid() {
        // Declares bit 64 but only one invalidation byte exists. Reporting
        // "all valid" would invent information, so no validity is reported.
        let sig = signal_with_invalidation(&[1, 2], &[0xFF, 0xFF], 64);
        assert_eq!(sig.validity(), None);
    }

    #[test]
    fn validity_accounts_for_the_record_id_offset() {
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 8;
        ch.conversion = Conversion::None;
        ch.invalidation_bit = true;
        ch.inval_bit_pos = 0;

        // record = [rec_id][value][inval]
        let raw = vec![7, 10, 0b0000_0001, 7, 20, 0b0000_0000];
        let sig = Signal::new(
            ch,
            Arc::new(raw),
            RecordLayout {
                record_size: 3,
                record_offset: 1,
                inval_start: 1,
                inval_bytes: 1,
            },
            2,
        );
        assert_eq!(sig.validity(), Some(vec![false, true]));
    }

    #[test]
    fn invalid_samples_are_still_returned_by_values() {
        // Documented behaviour: values() does not filter. Callers combine it
        // with validity() themselves.
        let sig = signal_with_invalidation(&[10, 20], &[0, 1], 0);
        let v = sig.values().unwrap();
        assert_eq!(v.len(), 2, "invalid samples are present, not dropped");
        assert_eq!(v.to_f64(), vec![10.0, 20.0]);
    }
    /// Deterministic byte source, so a disagreement is reproducible.
    fn pseudo_bytes(n: usize, seed: u64) -> Vec<u8> {
        let mut x = seed | 1;
        (0..n)
            .map(|_| {
                x ^= x << 13;
                x ^= x >> 7;
                x ^= x << 17;
                (x >> 33) as u8
            })
            .collect()
    }

    /// Builds the same signal twice, once decoded each way.
    #[allow(clippy::too_many_arguments)]
    fn both_paths(
        data_type: DataType,
        bit_count: u32,
        bit_offset: u8,
        byte_offset: u32,
        record_size: usize,
        conversion: Conversion,
        raw: Vec<u8>,
        samples: usize,
    ) -> (SignalValues, SignalValues) {
        let mut ch = create_test_channel();
        ch.data_type = data_type;
        ch.bit_count = bit_count;
        ch.bit_offset = bit_offset;
        ch.byte_offset = byte_offset;
        ch.conversion = conversion;

        let layout = RecordLayout {
            record_size,
            record_offset: 0,
            inval_start: record_size,
            inval_bytes: 0,
        };

        let fast = Signal::new(ch.clone(), Arc::new(raw.clone()), layout, samples);
        let mut slow = Signal::new(ch, Arc::new(raw), layout, samples);
        slow.force_general = true;

        (fast.values().unwrap(), slow.values().unwrap())
    }

    #[test]
    fn raw_values_honours_the_record_offset_once() {
        // A sorted group with a record id puts each field after that id.
        // `raw_values` used to add the record offset on top of the one
        // already folded into `StridedField::offset`, reading every sample
        // one id late; this pins the fast and general paths agreeing.
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 32;
        ch.bit_offset = 0;
        ch.conversion = Conversion::None;

        let rec_id_size = 1usize;
        let record_size = 8; // id + u32 field + padding
        let samples = 32;
        let mut raw = pseudo_bytes(record_size * samples, 99);
        // Distinct per-sample values, so a one-record shift would be visible.
        for (i, chunk) in raw.chunks_exact_mut(record_size).enumerate() {
            chunk[rec_id_size..rec_id_size + 4].copy_from_slice(&(i as u32).to_le_bytes());
        }

        let layout = RecordLayout {
            record_size,
            record_offset: rec_id_size,
            inval_start: record_size,
            inval_bytes: 0,
        };

        let fast = Signal::new(ch.clone(), Arc::new(raw.clone()), layout, samples);
        let mut slow = Signal::new(ch, Arc::new(raw), layout, samples);
        slow.force_general = true;

        let fast_raw = fast.raw_values().unwrap();
        let slow_raw = slow.raw_values().unwrap();
        assert_eq!(
            fast_raw, slow_raw,
            "raw paths disagree under a record offset"
        );

        let expected: Vec<u32> = (0..samples as u32).collect();
        assert_eq!(fast_raw, SignalValues::U32(expected));
    }

    #[test]
    fn the_fast_path_agrees_with_the_general_path() {
        // Every width and signedness the strided path claims to handle, over
        // pseudo-random bytes. A disagreement here means one of the two decoders
        // is wrong, which no amount of speed would make acceptable.
        let cases: &[(DataType, u32)] = &[
            (DataType::UIntLe, 8),
            (DataType::UIntLe, 16),
            (DataType::UIntLe, 32),
            (DataType::UIntLe, 64),
            (DataType::IntLe, 8),
            (DataType::IntLe, 16),
            (DataType::IntLe, 32),
            (DataType::IntLe, 64),
            (DataType::FloatLe, 32),
            (DataType::FloatLe, 64),
        ];

        for (seed, &(dt, bits)) in cases.iter().enumerate() {
            let width = (bits / 8) as usize;
            let record_size = width + 3; // deliberately not tightly packed
            let samples = 64;
            let raw = pseudo_bytes(record_size * samples, seed as u64 + 1);

            let (fast, slow) =
                both_paths(dt, bits, 0, 0, record_size, Conversion::None, raw, samples);
            assert_eq!(fast, slow, "paths disagree for {dt:?} at {bits} bits");
        }
    }

    #[test]
    fn the_fast_path_agrees_with_the_general_path_for_packed_bitfields() {
        // The widths and offsets a CAN frame actually uses: a 2-bit bus number,
        // a 29-bit identifier at bit 2, single flag bits, a 4-bit length.
        let cases: &[(DataType, u32, u8)] = &[
            (DataType::UIntLe, 1, 0),
            (DataType::UIntLe, 1, 7),
            (DataType::UIntLe, 2, 0),
            (DataType::UIntLe, 4, 2),
            (DataType::UIntLe, 7, 1),
            (DataType::UIntLe, 29, 2),
            (DataType::UIntLe, 12, 4),
            (DataType::UIntLe, 33, 3),
            (DataType::IntLe, 5, 1),
            (DataType::IntLe, 12, 3),
            (DataType::IntLe, 20, 6),
        ];

        for (seed, &(dt, bits, bit_offset)) in cases.iter().enumerate() {
            let record_size = 16;
            let samples = 64;
            let raw = pseudo_bytes(record_size * samples, seed as u64 + 500);

            let (fast, slow) = both_paths(
                dt,
                bits,
                bit_offset,
                0,
                record_size,
                Conversion::None,
                raw,
                samples,
            );
            assert_eq!(
                fast, slow,
                "paths disagree for {dt:?} at {bits} bits, offset {bit_offset}"
            );
        }
    }

    #[test]
    fn the_fast_path_agrees_when_the_field_is_offset_within_the_record() {
        let record_size = 16;
        let samples = 32;
        let raw = pseudo_bytes(record_size * samples, 99);
        for byte_offset in [0u32, 1, 3, 8] {
            let (fast, slow) = both_paths(
                DataType::UIntLe,
                32,
                0,
                byte_offset,
                record_size,
                Conversion::None,
                raw.clone(),
                samples,
            );
            assert_eq!(fast, slow, "paths disagree at byte offset {byte_offset}");
        }
    }

    #[test]
    fn the_fast_path_agrees_with_a_linear_conversion() {
        let record_size = 8;
        let samples = 48;
        let raw = pseudo_bytes(record_size * samples, 7);
        let (fast, slow) = both_paths(
            DataType::FloatLe,
            64,
            0,
            0,
            record_size,
            Conversion::Linear {
                offset: -3.5,
                factor: 1e-9,
            },
            raw,
            samples,
        );
        assert_eq!(fast, slow, "linear conversion differs between paths");
    }

    #[test]
    fn packed_bitfields_are_read_strided() {
        // A 29-bit identifier starting at bit 2 is the shape most of a bus log
        // takes, so it must not fall back to per-sample bit extraction.
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 29;
        ch.bit_offset = 2;
        ch.conversion = Conversion::None;
        let sig = Signal::new(ch, Arc::new(vec![0xFFu8; 64]), plain(8), 4);
        assert!(sig.strided_offset().is_some());
    }

    #[test]
    fn fields_the_strided_reader_cannot_handle_use_the_general_path() {
        // Big-endian needs its bytes reversed, which the strided reader does
        // not do.
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntBe;
        ch.bit_count = 32;
        ch.conversion = Conversion::None;
        let sig = Signal::new(ch, Arc::new(vec![0u8; 64]), plain(8), 4);
        assert!(sig.strided_offset().is_none(), "big-endian is not strided");

        // A field whose bit offset pushes it past eight bytes cannot be
        // assembled into a u64.
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 64;
        ch.bit_offset = 4;
        ch.conversion = Conversion::None;
        let sig = Signal::new(ch, Arc::new(vec![0u8; 128]), plain(16), 4);
        assert!(
            sig.strided_offset().is_none(),
            "68 bits do not fit in a u64"
        );
    }

    #[test]
    fn a_truncated_final_record_falls_back_rather_than_reading_past_the_end() {
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 32;
        ch.conversion = Conversion::None;
        // 4 samples at stride 8 read up to byte 28, so 30 bytes would in fact
        // be enough; 26 is genuinely short of the final record.
        let sig = Signal::new(ch.clone(), Arc::new(vec![0u8; 26]), plain(8), 4);
        assert!(
            sig.strided_offset().is_none(),
            "a buffer too short for the last record must not be read strided"
        );

        // The boundary case: exactly enough for the last field.
        let sig = Signal::new(ch, Arc::new(vec![0u8; 28]), plain(8), 4);
        assert!(
            sig.strided_offset().is_some(),
            "a buffer ending exactly at the last field is fine"
        );
    }
    /// A variable-length channel: an 8-byte offset per record, with payloads
    /// supplied separately.
    fn vlsd_signal(offsets: &[u64], payload_stream: &[u8]) -> Signal {
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::VariableLength;
        ch.data_type = DataType::MimeSample;
        ch.bit_count = 64;
        ch.byte_offset = 0;
        ch.conversion = Conversion::None;

        let mut raw = Vec::new();
        for o in offsets {
            raw.extend_from_slice(&o.to_le_bytes());
        }

        let mut sig = Signal::new(ch, Arc::new(raw), plain(8), offsets.len());
        sig.attach_payloads(Arc::new(VlsdPayloads::from_stream(payload_stream)));
        sig
    }

    fn payload_stream(payloads: &[&[u8]]) -> Vec<u8> {
        let mut out = Vec::new();
        for p in payloads {
            out.extend_from_slice(&(p.len() as u32).to_le_bytes());
            out.extend_from_slice(p);
        }
        out
    }

    #[test]
    fn variable_length_payloads_of_one_size_become_fixed_width_bytes() {
        let stream = payload_stream(&[&[1, 2, 3, 4], &[5, 6, 7, 8]]);
        let sig = vlsd_signal(&[0, 8], &stream);

        match sig.values().unwrap() {
            SignalValues::Bytes { data, width } => {
                assert_eq!(width, 4);
                assert_eq!(data, vec![1, 2, 3, 4, 5, 6, 7, 8]);
            }
            other => panic!("expected fixed-width Bytes, got {}", other.kind().name()),
        }
    }

    #[test]
    fn variable_length_payloads_of_mixed_sizes_stay_variable() {
        // Padding the short one out would invent bytes the file does not have.
        let stream = payload_stream(&[&[1, 2, 3], &[4, 5, 6, 7, 8]]);
        let sig = vlsd_signal(&[0, 7], &stream);

        let values = sig.values().unwrap();
        assert!(matches!(values, SignalValues::VarBytes { .. }));
        assert_eq!(values.len(), 2);
        assert_eq!(values.bytes_at(0), Some(&[1, 2, 3][..]));
        assert_eq!(values.bytes_at(1), Some(&[4, 5, 6, 7, 8][..]));
    }

    #[test]
    fn variable_length_payloads_of_a_string_channel_decode_as_text() {
        // Both payloads are three bytes, so the fixed-width path would have
        // claimed them and reported a byte blob for a channel that declares
        // UTF-8 text — which is what a vendor file caught this reader doing.
        let stream = payload_stream(&[b"abc", b"def"]);
        let mut sig = vlsd_signal(&[0, 7], &stream);
        sig.channel.data_type = DataType::StringUtf8;

        match sig.values().unwrap() {
            SignalValues::Str(v) => assert_eq!(v, vec!["abc".to_string(), "def".to_string()]),
            other => panic!("expected Str, got {}", other.kind().name()),
        }
    }

    #[test]
    fn a_zero_width_fixed_length_blob_fails_rather_than_panicking() {
        // B1. A channel declaring `cn_bit_count == 0` is zero bytes wide, and
        // the fixed-width bytes path handed `chunks_exact_mut` a chunk size of
        // 0, which panics. There is nothing readable in such a channel, so it
        // must report that instead of crashing the reader.
        let mut ch = create_test_channel();
        ch.data_type = DataType::ByteArray;
        ch.bit_count = 0;
        ch.byte_offset = 0;
        ch.conversion = Conversion::None;

        let sig = Signal::new(ch, Arc::new(vec![0u8; 128]), plain(4), 4);
        assert!(
            sig.values().is_err(),
            "a zero-width byte channel must fail rather than panic"
        );
    }

    #[test]
    fn an_all_empty_payload_stream_decodes_to_empty_samples() {
        // Every payload empty makes `uniform_len` report width 0, and the
        // uniform path handed `chunks_exact_mut` an empty chunk size, which
        // panicked. An empty sample is not corruption, though — it is what a
        // missing or zero-byte payload already decodes to — so the channel must
        // come back as two empty samples rather than crash or fail the file.
        let stream = payload_stream(&[&[], &[]]);
        let sig = vlsd_signal(&[0, 4], &stream);

        let values = sig.values().unwrap();
        assert_eq!(values.len(), 2);
        assert_eq!(values.bytes_at(0), Some(&[][..]));
        assert_eq!(values.bytes_at(1), Some(&[][..]));
    }

    #[test]
    fn uniform_payloads_wider_than_the_offset_word_decode() {
        // The allocation ceiling for the uniform path was once measured against
        // the records' `raw_data`, which holds only the 8-byte offsets. A
        // payload wider than one bought false "truncated" errors — a CAN-FD
        // frame of 16, 32 or 64 bytes failed while its file was fine.
        let stream = payload_stream(&[&[0u8; 16], &[0xFFu8; 16]]);
        let sig = vlsd_signal(&[0, 20], &stream);

        let values = sig.values().unwrap();
        assert_eq!(values.len(), 2);
        assert_eq!(values.bytes_at(0), Some(&[0u8; 16][..]));
        assert_eq!(values.bytes_at(1), Some(&[0xFFu8; 16][..]));
    }

    #[test]
    fn the_payload_offset_is_read_little_endian_whatever_the_channel_type_says() {
        // MimeSample is not a little-endian type, but the offset pointing at the
        // payload is still stored little-endian. Reading it through the
        // channel's endianness yields a byte-reversed offset that resolves to
        // nothing — which is exactly what happened before this was fixed.
        let stream = payload_stream(&[&[0xAA], &[0xBB]]);
        let sig = vlsd_signal(&[0, 5], &stream);

        let values = sig.values().unwrap();
        assert_eq!(values.bytes_at(0), Some(&[0xAA][..]));
        assert_eq!(values.bytes_at(1), Some(&[0xBB][..]));
    }

    #[test]
    fn an_offset_pointing_nowhere_yields_an_empty_sample() {
        let stream = payload_stream(&[&[1, 2]]);
        let sig = vlsd_signal(&[0, 9999], &stream);

        let values = sig.values().unwrap();
        assert_eq!(values.len(), 2);
        assert_eq!(values.bytes_at(0), Some(&[1, 2][..]));
        assert_eq!(
            values.bytes_at(1),
            Some(&[][..]),
            "an unresolvable offset must not drop the sample or shift the rest"
        );
    }

    #[test]
    fn a_variable_length_channel_without_payloads_fails_rather_than_guessing() {
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::VariableLength;
        ch.bit_count = 64;
        let sig = Signal::new(ch, Arc::new(vec![0u8; 16]), plain(8), 2);
        assert!(sig.values().is_err());
    }
    #[test]
    fn big_endian_channels_decode_through_the_general_path() {
        // No corpus file contains a big-endian channel, so this is the only
        // coverage the whole-signal path gets for one. The strided reader
        // declines big-endian deliberately, so this also pins that fallback.
        let mut ch = create_test_channel();
        ch.data_type = DataType::UIntBe;
        ch.bit_count = 16;
        ch.byte_offset = 0;
        ch.conversion = Conversion::None;

        // Two records of [0x12,0x34] and [0xAB,0xCD], stride 4.
        let raw = vec![0x12, 0x34, 0, 0, 0xAB, 0xCD, 0, 0];
        let sig = Signal::new(ch, Arc::new(raw), plain(4), 2);

        assert!(
            sig.strided_offset().is_none(),
            "big-endian must not take the strided path"
        );
        assert_eq!(
            sig.values().unwrap(),
            SignalValues::U16(vec![0x1234, 0xABCD])
        );
    }

    #[test]
    fn big_endian_and_little_endian_channels_disagree_over_the_same_bytes() {
        let raw = vec![0x12u8, 0x34, 0, 0];

        let mut be = create_test_channel();
        be.data_type = DataType::UIntBe;
        be.bit_count = 16;
        be.conversion = Conversion::None;
        let be_values = Signal::new(be, Arc::new(raw.clone()), plain(4), 1)
            .values()
            .unwrap();

        let mut le = create_test_channel();
        le.data_type = DataType::UIntLe;
        le.bit_count = 16;
        le.conversion = Conversion::None;
        let le_values = Signal::new(le, Arc::new(raw), plain(4), 1)
            .values()
            .unwrap();

        assert_eq!(be_values, SignalValues::U16(vec![0x1234]));
        assert_eq!(le_values, SignalValues::U16(vec![0x3412]));
    }

    #[test]
    fn a_signed_big_endian_channel_sign_extends() {
        let mut ch = create_test_channel();
        ch.data_type = DataType::IntBe;
        ch.bit_count = 16;
        ch.conversion = Conversion::None;
        let raw = vec![0xFFu8, 0xFF, 0, 0, 0x00, 0x7F, 0, 0];
        let sig = Signal::new(ch, Arc::new(raw), plain(4), 2);
        assert_eq!(sig.values().unwrap(), SignalValues::I16(vec![-1, 127]));
    }

    #[test]
    fn a_big_endian_float_channel_decodes() {
        let mut ch = create_test_channel();
        ch.data_type = DataType::FloatBe;
        ch.bit_count = 64;
        ch.conversion = Conversion::None;
        let mut raw = 1.5f64.to_be_bytes().to_vec();
        raw.extend_from_slice(&(-0.25f64).to_be_bytes());
        let sig = Signal::new(ch, Arc::new(raw), plain(8), 2);
        assert_eq!(sig.values().unwrap(), SignalValues::F64(vec![1.5, -0.25]));
    }
    #[test]
    fn a_maximum_length_channel_naming_no_length_channel_cannot_be_decoded() {
        // Without the channel that counts each sample's bytes there is nothing
        // to bound the data with, so the samples cannot be separated from the
        // unused remainder of the field. Decoding it as a fixed-width value
        // would return real-looking numbers from the wrong bytes.
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::MaxLength;
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 32;
        ch.conversion = Conversion::None;

        let sig = Signal::new(ch, Arc::new(vec![0xFFu8; 32]), plain(8), 4);
        match sig.values() {
            Err(Mf4Error::Unsupported { feature, .. }) => {
                assert!(feature.contains("MLSD"), "unexpected feature: {feature}")
            }
            Err(e) => panic!("expected an Unsupported error, got {e}"),
            Ok(_) => panic!("an MLSD channel must not decode as fixed-length"),
        }
    }

    #[test]
    fn a_synchronisation_channel_decodes_its_samples() {
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::Sync;
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 32;
        ch.conversion = Conversion::None;

        let mut data = Vec::new();
        for i in 0..4u32 {
            data.extend_from_slice(&i.to_le_bytes());
            data.extend_from_slice(&0u32.to_le_bytes()); // 8-byte record stride
        }

        let sig = Signal::new(ch, Arc::new(data), plain(8), 4);
        let values = sig.values_f64().expect("sync channel should decode");
        assert_eq!(values, vec![0.0, 1.0, 2.0, 3.0]);
    }

    #[test]
    fn an_unrecognised_data_type_is_refused_rather_than_read_as_bytes() {
        // 4.9.1. Codes 0–15 are the whole of the 4.11 set, so 16 is either a
        // later revision or a corrupt field. Either way its width, signedness
        // and byte order are unknown, and reporting it as a byte array would be
        // a confident answer to an unanswerable question.
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::FixedLength;
        ch.data_type = DataType::Unknown(16);
        ch.bit_count = 32;
        ch.byte_offset = 0;
        ch.conversion = Conversion::None;

        let sig = Signal::new(ch, Arc::new(vec![7u8; 32]), plain(4), 4);
        match sig.values() {
            Err(Mf4Error::Unsupported { feature, .. }) => {
                assert!(feature.contains("16"), "the error should name the code");
            }
            Err(e) => panic!("expected an Unsupported error, got {e}"),
            Ok(v) => panic!("an unknown data type must not decode, got {v:?}"),
        }
    }

    #[test]
    fn a_master_channel_still_decodes_from_the_record() {
        // A stored master channel is an ordinary fixed-length read. The guards
        // above must not catch it, and the virtual rule below must not either.
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::Master;
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 8;
        ch.byte_offset = 0;
        ch.conversion = Conversion::None;

        let sig = Signal::new(ch, Arc::new(vec![7u8; 8]), plain(2), 4);
        assert_eq!(sig.values().unwrap(), SignalValues::U8(vec![7, 7, 7, 7]));
    }

    #[test]
    fn a_virtual_channel_takes_its_raw_value_from_the_sample_index() {
        // B21. A virtual channel occupies no bytes: `cn_bit_count` is 0 and the
        // raw value is the sample's index. Reading the record instead yields 0
        // for every sample, which the corpus cannot distinguish because every
        // virtual channel in it has a conversion factor of 0.
        for channel_type in [ChannelType::VirtualMaster, ChannelType::VirtualData] {
            let mut ch = create_test_channel();
            ch.channel_type = channel_type;
            ch.data_type = DataType::UIntLe;
            ch.bit_count = 0;
            ch.byte_offset = 0;
            ch.conversion = Conversion::None;

            // The record bytes are deliberately non-zero: if the decoder reads
            // them, the result is 7s rather than a ramp.
            let sig = Signal::new(ch, Arc::new(vec![7u8; 8]), plain(2), 4);
            assert_eq!(
                sig.values().unwrap(),
                SignalValues::U64(vec![0, 1, 2, 3]),
                "{channel_type:?} must count samples, not read the record"
            );
        }
    }

    #[test]
    fn a_virtual_channels_conversion_applies_to_its_index() {
        // The point of a virtual master: a time base of 10 ms steps stored as
        // nothing but a factor. A factor of 0 — every case the corpus has —
        // would collapse this to a constant and hide the bug.
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::VirtualMaster;
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 0;
        ch.byte_offset = 0;
        ch.conversion = Conversion::Linear {
            offset: 5.0,
            factor: 0.01,
        };

        let sig = Signal::new(ch, Arc::new(vec![7u8; 8]), plain(2), 4);
        assert_eq!(
            sig.values().unwrap(),
            SignalValues::F64(vec![5.0, 5.01, 5.02, 5.03])
        );
    }

    #[test]
    fn a_virtual_index_past_the_eighth_bit_is_not_truncated() {
        // `value_kind` sizes an identity channel from its bit count, which is 0
        // here. Sizing the index that way would report `u8` and wrap at 256.
        let mut ch = create_test_channel();
        ch.channel_type = ChannelType::VirtualData;
        ch.data_type = DataType::UIntLe;
        ch.bit_count = 0;
        ch.byte_offset = 0;
        ch.conversion = Conversion::None;

        let sig = Signal::new(ch, Arc::new(Vec::new()), plain(0), 300);
        let SignalValues::U64(values) = sig.values().unwrap() else {
            panic!("a virtual channel's index must be reported as u64");
        };
        assert_eq!(values.len(), 300);
        assert_eq!(values[299], 299);
    }
}