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
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
//! MDF File Indexing System
//!
//! This module provides functionality to create lightweight indexes of MDF files
//! that can be serialized to JSON and used later to read specific channel data
//! without parsing the entire file structure.
use serde::{Deserialize, Serialize};
use crate::api::mdf::Mdf;
use crate::blocks::common::{DataType, BlockHeader, BlockParse};
use crate::blocks::conversion::{ConversionBlock, ConversionType};
use crate::error::MdfError;
use crate::parsing::decoder::{check_value_validity, decode_channel_value, decode_channel_value_with_validity, decode_f64_from_record, DecodedValue};
use crate::signal::{decoded_opt_to_f64, Signal};
use crate::types::{resolve_records, ChannelInfo, ConversionInfo, GroupInfo, ReadOptions, TimeRange, Window};
/// Largest single read issued when coalescing adjacent data blocks (64 MiB).
const MAX_COALESCED_READ: u64 = 64 * 1024 * 1024;
/// Represents the location and metadata of data blocks in the file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataBlockInfo {
/// File offset where the data block starts
pub file_offset: u64,
/// Size of the data block in bytes
pub size: u64,
/// Whether this is a compressed block (DZ)
pub is_compressed: bool,
}
/// Channel metadata needed for decoding values
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexedChannel {
/// Channel name
pub name: Option<String>,
/// Physical unit
pub unit: Option<String>,
/// Channel comment (`##TX` text, or the raw `##MD` XML)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
/// Data type of the channel
pub data_type: DataType,
/// Byte offset within each record
pub byte_offset: u32,
/// Bit offset within the byte
pub bit_offset: u8,
/// Number of bits for this channel
pub bit_count: u32,
/// Channel type (0=data, 1=VLSD, 2=master, etc.)
pub channel_type: u8,
/// Channel flags (includes invalidation bit flags)
pub flags: u32,
/// Position of invalidation bit within invalidation bytes
pub pos_invalidation_bit: u32,
/// Conversion block for unit conversion (if any).
///
/// May be `None` even when the channel *has* a conversion: index builds
/// that read a file over the network ([`MdfIndex::from_url`] /
/// [`MdfIndex::from_range_reader`]) do **not** fetch and resolve the
/// conversion block up front — they only record its file offset in
/// [`conversion_addr`](Self::conversion_addr) and resolve it lazily on the
/// first value read. Indexes built from a local file or an in-memory buffer
/// still resolve eagerly, so this stays populated for them. Read paths
/// prefer a resolved conversion here and otherwise fall back to
/// `conversion_addr`.
pub conversion: Option<ConversionBlock>,
/// File offset of the channel's `##CC` conversion block (0 = none).
///
/// Recorded so the conversion can be resolved lazily at read time when it
/// was not resolved during index building (the remote / range-reader
/// path). Defaults to 0 for older serialized indexes, which carry the fully
/// resolved [`conversion`](Self::conversion) instead.
#[serde(default)]
pub conversion_addr: u64,
/// For VLSD channels: address of signal data blocks
pub vlsd_data_address: Option<u64>,
/// For VLSD channels: locations of the ##SD fragments in chain order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub vlsd_data_blocks: Vec<DataBlockInfo>,
}
impl IndexedChannel {
/// `true` if this is the group's master channel (usually time): a
/// regular (`cn_type` 2) or virtual (`cn_type` 3) master.
pub fn is_master(&self) -> bool {
self.channel_type == 2 || self.channel_type == 3
}
/// `true` for a virtual channel (`cn_type` 3 master or 6 data): it stores
/// no bytes, its raw value is the record index.
pub fn is_virtual(&self) -> bool {
self.channel_type == 3 || self.channel_type == 6
}
/// This channel's metadata as a plain [`ChannelInfo`].
pub fn info(&self) -> ChannelInfo {
ChannelInfo {
name: self.name.clone(),
unit: self.unit.clone(),
comment: self.comment.clone(),
data_type: self.data_type.name().to_string(),
bit_count: self.bit_count,
is_master: self.is_master(),
is_vlsd: self.is_vlsd(),
has_conversion: self.conversion.is_some() || self.conversion_addr != 0,
}
}
/// `true` if this is a variable-length (VLSD) channel.
pub fn is_vlsd(&self) -> bool {
self.channel_type == 1 && self.vlsd_data_address.is_some()
}
/// Create a temporary `ChannelBlock` for use with the decoder functions.
/// This should be called once and reused across all records.
fn to_channel_block(&self) -> crate::blocks::channel_block::ChannelBlock {
Self::build_channel_block(
self.channel_type,
self.data_type.clone(),
self.bit_offset,
self.byte_offset,
self.bit_count,
self.flags,
self.pos_invalidation_bit,
self.name.clone(),
self.conversion.clone(),
)
}
/// Create a lightweight `ChannelBlock` for decode-only use (f64 fast path).
/// Skips cloning the name and conversion since the decoder doesn't use them.
fn to_decode_only_channel_block(&self) -> crate::blocks::channel_block::ChannelBlock {
Self::build_channel_block(
self.channel_type,
self.data_type.clone(),
self.bit_offset,
self.byte_offset,
self.bit_count,
self.flags,
self.pos_invalidation_bit,
None,
None,
)
}
fn build_channel_block(
channel_type: u8,
data_type: DataType,
bit_offset: u8,
byte_offset: u32,
bit_count: u32,
flags: u32,
pos_invalidation_bit: u32,
name: Option<String>,
conversion: Option<ConversionBlock>,
) -> crate::blocks::channel_block::ChannelBlock {
crate::blocks::channel_block::ChannelBlock {
header: crate::blocks::common::BlockHeader {
id: "##CN".to_string(),
reserved0: 0,
block_len: 160,
links_nr: 8,
},
next_ch_addr: 0,
component_addr: 0,
name_addr: 0,
source_addr: 0,
conversion_addr: 0,
data: 0,
unit_addr: 0,
comment_addr: 0,
channel_type,
sync_type: 0,
data_type,
bit_offset,
byte_offset,
bit_count,
flags,
pos_invalidation_bit,
precision: 0,
reserved1: 0,
attachment_nr: 0,
min_raw_value: 0.0,
max_raw_value: 0.0,
lower_limit: 0.0,
upper_limit: 0.0,
lower_ext_limit: 0.0,
upper_ext_limit: 0.0,
name,
conversion,
}
}
}
/// Channel group metadata and layout information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexedChannelGroup {
/// Group name
pub name: Option<String>,
/// Comment
pub comment: Option<String>,
/// Size of record ID in bytes
pub record_id_len: u8,
/// Total size of each record in bytes (excluding record ID and invalidation bytes)
pub record_size: u32,
/// Number of invalidation bytes per record
pub invalidation_bytes: u32,
/// Number of records in this group
pub record_count: u64,
/// Channels in this group
pub channels: Vec<IndexedChannel>,
/// Data block locations for this channel group
pub data_blocks: Vec<DataBlockInfo>,
/// Index (into [`MdfIndex::channel_groups`]) of the group holding this
/// group's master channel when it is stored *remotely* — the MDF 4.2
/// column-oriented layout, where each signal has its own channel group and
/// points at a shared time group via `cg_cg_master`. `None` when the master
/// is local (or there is none).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub master_group: Option<usize>,
}
impl IndexedChannelGroup {
/// Find a channel in this group by name (first match).
pub fn channel(&self, name: &str) -> Option<&IndexedChannel> {
self.channels
.iter()
.find(|c| c.name.as_deref() == Some(name))
}
/// Names of every named channel in this group, in record order.
pub fn channel_names(&self) -> Vec<&str> {
self.channels
.iter()
.filter_map(|c| c.name.as_deref())
.collect()
}
/// The group's master channel (channel type 2), if any.
pub fn master_channel(&self) -> Option<&IndexedChannel> {
self.channels.iter().find(|c| c.is_master())
}
}
/// Where an [`MdfIndex`] reads sample data from when asked to.
///
/// The source is *not* serialized with the index — after [`MdfIndex::load`]
/// re-attach one with [`MdfIndex::set_source`]. Building an
/// index never reads sample data; the actual byte-range reads happen lazily on
/// [`MdfIndex::read`].
#[derive(Debug, Clone)]
pub enum Source {
/// A local file path, read via memory map.
File(String),
/// An HTTP/S3 URL, read via range requests.
#[cfg(feature = "http")]
Url(String),
}
impl Source {
/// The file path or URL as a string.
pub fn as_str(&self) -> &str {
match self {
Source::File(p) => p,
#[cfg(feature = "http")]
Source::Url(u) => u,
}
}
}
/// A string is a [`Source`]: `http://` / `https://` URLs become
/// [`Source::Url`] (with the `http` feature), anything else a file path.
impl From<&str> for Source {
fn from(value: &str) -> Self {
#[cfg(feature = "http")]
if value.starts_with("http://") || value.starts_with("https://") {
return Source::Url(value.to_string());
}
Source::File(value.to_string())
}
}
impl From<String> for Source {
fn from(value: String) -> Self {
Source::from(value.as_str())
}
}
/// Reader over an index's attached [`Source`], for windowed reads.
enum SourceReader {
#[cfg(not(target_arch = "wasm32"))]
File(MmapRangeReader),
#[cfg(feature = "http")]
Url(CachingRangeReader<HttpRangeReader>),
}
impl ByteRangeReader for SourceReader {
type Error = MdfError;
#[allow(unused_variables)]
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
match *self {
#[cfg(not(target_arch = "wasm32"))]
SourceReader::File(ref mut r) => r.read_range(offset, length),
#[cfg(feature = "http")]
SourceReader::Url(ref mut r) => r.read_range(offset, length),
}
}
}
/// Complete MDF file index
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MdfIndex {
/// File size for validation
pub file_size: u64,
/// Start time of the measurement in nanoseconds since epoch (from MDF header)
/// None if the start time is not set (0) in the file
pub start_time_ns: Option<u64>,
/// Channel groups in the file
pub channel_groups: Vec<IndexedChannelGroup>,
/// The data source for lazy value reads. Populated by `from_file` /
/// `from_url`, re-attachable after load via `set_source`. Never
/// serialized — an index file is portable; the source is environment-local.
#[serde(skip)]
pub source: Option<Source>,
}
/// Trait for reading byte ranges from different sources (files, HTTP, etc.)
pub trait ByteRangeReader {
type Error;
/// Read bytes from the specified range
/// Returns the requested bytes or an error
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error>;
/// Read an *optional* metadata range that the walk can proceed without.
///
/// Behaves exactly like [`read_range`](Self::read_range) by default, so
/// on-demand readers (file, HTTP) are unaffected. Incremental readers that
/// *gather* the ranges they still need — rather than fetching one at a time
/// — override this to record a gap and return `Ok(None)` instead of
/// aborting. That lets a single metadata walk collect **every** still-missing
/// leaf range (channel names, units, group comments) at once, turning an
/// O(N²) fetch-restart loop into a handful of passes. Returning `None` means
/// "these bytes are not available yet"; the caller treats the value as
/// absent for this pass. Structural reads (block headers whose bytes yield
/// the next link address) must keep using [`read_range`](Self::read_range) —
/// the walk cannot continue past those without the real bytes.
fn read_range_optional(
&mut self,
offset: u64,
length: u64,
) -> Result<Option<Vec<u8>>, Self::Error> {
self.read_range(offset, length).map(Some)
}
/// True when this reader is a gap-discovery probe: it cannot serve every
/// range and records the misses instead of returning data. Metadata walks
/// may then skip an unreadable subtree and keep discovering gaps elsewhere
/// rather than aborting on the first miss.
///
/// A walk driven by a probing reader produces a **partial** result: callers
/// MUST discard it and retry once the recorded ranges have been supplied.
fn is_probing(&self) -> bool {
false
}
}
/// Local file reader implementation.
///
/// Not available on `wasm32-unknown-unknown`; implement [`ByteRangeReader`] over
/// a `Cursor<Vec<u8>>` or a JS `Blob`-backed reader instead.
#[cfg(not(target_arch = "wasm32"))]
pub struct FileRangeReader {
file: std::fs::File,
}
#[cfg(not(target_arch = "wasm32"))]
impl FileRangeReader {
pub fn new(file_path: &str) -> Result<Self, MdfError> {
let file = std::fs::File::open(file_path)
.map_err(MdfError::IOError)?;
Ok(Self { file })
}
}
#[cfg(not(target_arch = "wasm32"))]
impl ByteRangeReader for FileRangeReader {
type Error = MdfError;
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
use std::io::{Read, Seek, SeekFrom};
// Validate against the real file length *before* allocating: a forged
// or stale index could otherwise request an absurd length and abort
// the process on allocation failure.
let file_len = self.file.metadata().map_err(MdfError::IOError)?.len();
match offset.checked_add(length) {
Some(end) if end <= file_len => {}
_ => {
return Err(MdfError::TooShortBuffer {
actual: file_len as usize,
expected: offset.saturating_add(length) as usize,
file: file!(),
line: line!(),
});
}
}
self.file.seek(SeekFrom::Start(offset))
.map_err(MdfError::IOError)?;
let mut buffer = vec![0u8; length as usize];
self.file.read_exact(&mut buffer)
.map_err(MdfError::IOError)?;
Ok(buffer)
}
}
/// Memory-mapped file reader implementation.
///
/// Not available on `wasm32-unknown-unknown`.
#[cfg(not(target_arch = "wasm32"))]
pub struct MmapRangeReader {
mmap: memmap2::Mmap,
}
#[cfg(not(target_arch = "wasm32"))]
impl MmapRangeReader {
pub fn new(file_path: &str) -> Result<Self, MdfError> {
let file = std::fs::File::open(file_path).map_err(MdfError::IOError)?;
let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
Ok(Self { mmap })
}
}
#[cfg(not(target_arch = "wasm32"))]
impl ByteRangeReader for MmapRangeReader {
type Error = MdfError;
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
// Checked arithmetic: a forged offset/length must error, not wrap.
let end = match offset
.checked_add(length)
.and_then(|e| usize::try_from(e).ok())
{
Some(end) if end <= self.mmap.len() => end,
_ => {
return Err(MdfError::TooShortBuffer {
actual: self.mmap.len(),
expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
file: file!(),
line: line!(),
});
}
};
Ok(self.mmap[offset as usize..end].to_vec())
}
}
/// In-memory byte-slice reader — available on all targets including WASM.
///
/// Wraps an owned `Vec<u8>` and satisfies [`ByteRangeReader`] by slicing
/// directly into it. Useful when the entire file has already been loaded
/// into memory (e.g. via `Blob.arrayBuffer()` in a browser Worker).
pub struct SliceRangeReader {
data: Vec<u8>,
}
impl SliceRangeReader {
pub fn new(data: Vec<u8>) -> Self {
Self { data }
}
}
impl ByteRangeReader for SliceRangeReader {
type Error = MdfError;
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
// Checked arithmetic: a forged offset/length must error, not wrap.
let end = match offset
.checked_add(length)
.and_then(|e| usize::try_from(e).ok())
{
Some(end) if end <= self.data.len() => end,
_ => {
return Err(MdfError::TooShortBuffer {
actual: self.data.len(),
expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
file: file!(),
line: line!(),
});
}
};
Ok(self.data[offset as usize..end].to_vec())
}
}
/// Borrowing counterpart to [`SliceRangeReader`] — a [`ByteRangeReader`] over a
/// borrowed `&[u8]` (e.g. a memory map), so the mmap-based index paths can
/// reuse the generic reader logic without cloning the whole file into a `Vec`.
struct BorrowedSliceReader<'a> {
data: &'a [u8],
}
impl<'a> ByteRangeReader for BorrowedSliceReader<'a> {
type Error = MdfError;
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
// Checked arithmetic: a forged offset/length must error, not wrap.
let end = match offset
.checked_add(length)
.and_then(|e| usize::try_from(e).ok())
{
Some(end) if end <= self.data.len() => end,
_ => {
return Err(MdfError::TooShortBuffer {
actual: self.data.len(),
expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
file: file!(),
line: line!(),
});
}
};
Ok(self.data[offset as usize..end].to_vec())
}
}
/// Caching wrapper around any [`ByteRangeReader`].
///
/// During the metadata phase of building an [`MdfIndex`], the parser issues
/// many small reads (block headers, channel metadata, text blocks). Without
/// caching, each becomes a round-trip on a remote backend. `CachingRangeReader`
/// fetches in larger aligned chunks (default 1 MiB) and serves overlapping
/// reads from memory, collapsing hundreds of small reads into a handful of
/// underlying requests.
///
/// For value reads — which span large slices of data blocks — call
/// [`CachingRangeReader::set_bypass`] to forward each read directly to the
/// underlying reader without populating the cache.
pub struct CachingRangeReader<R: ByteRangeReader<Error = MdfError>> {
inner: R,
chunks: std::collections::BTreeMap<u64, Vec<u8>>,
chunk_size: u64,
bypass: bool,
underlying_requests: u64,
cache_hits: u64,
/// Total size of the underlying resource, once learned. Whole-chunk
/// fetches are clamped against it so strict inner readers (which error on
/// reads past EOF) still work when the resource size is not a multiple of
/// `chunk_size`.
known_size: Option<u64>,
}
impl<R: ByteRangeReader<Error = MdfError>> CachingRangeReader<R> {
/// Wrap a reader with the default chunk size (1 MiB).
pub fn new(inner: R) -> Self {
Self::with_chunk_size(inner, 1 << 20)
}
/// Wrap a reader with a custom chunk size in bytes.
pub fn with_chunk_size(inner: R, chunk_size: u64) -> Self {
assert!(chunk_size > 0, "chunk_size must be > 0");
Self {
inner,
chunks: std::collections::BTreeMap::new(),
chunk_size,
bypass: false,
underlying_requests: 0,
cache_hits: 0,
known_size: None,
}
}
/// Tell the cache the total size of the underlying resource (e.g. from an
/// HTTP size probe), so the final chunk is requested at its true length
/// instead of failing short and being re-requested.
pub fn set_known_size(&mut self, size: u64) {
self.known_size = Some(size);
}
/// When set, reads are served from already-cached chunks when fully
/// covered, and otherwise forward directly to the underlying reader without
/// populating the cache. Use during value-read phases so large data-block
/// fetches do not pollute the cache, while small metadata reads that were
/// already pulled in during the index walk (such as a conversion block
/// resolved lazily on first read) remain free.
pub fn set_bypass(&mut self, bypass: bool) {
self.bypass = bypass;
}
/// Number of read calls forwarded to the underlying reader.
pub fn underlying_requests(&self) -> u64 {
self.underlying_requests
}
/// Number of read calls fully satisfied from cache.
pub fn cache_hits(&self) -> u64 {
self.cache_hits
}
/// Pre-fetch a contiguous range into the cache.
pub fn prefetch(&mut self, offset: u64, length: u64) -> Result<(), MdfError> {
if length == 0 {
return Ok(());
}
self.read_range(offset, length).map(|_| ())
}
/// Try to satisfy a read entirely from chunks already in the cache,
/// without issuing any underlying request. Returns `None` if any covering
/// chunk is absent or too short (e.g. an EOF-clamped tail), leaving the
/// caller to fetch. Used in bypass mode so small reads that land in
/// already-fetched metadata chunks (e.g. a lazily-resolved conversion
/// block) stay free, while large uncached data reads still forward straight
/// through.
fn try_serve_from_cache(&self, offset: u64, length: u64) -> Option<Vec<u8>> {
let first = offset / self.chunk_size;
let last = (offset + length - 1) / self.chunk_size;
let read_end = offset + length;
for i in first..=last {
let chunk = self.chunks.get(&i)?;
let chunk_start = i * self.chunk_size;
let cached_end = chunk_start + chunk.len() as u64;
let needed_end = read_end.min(chunk_start + self.chunk_size);
if cached_end < needed_end {
return None;
}
}
let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
let mut remaining = length as usize;
let mut cursor = offset;
while remaining > 0 {
let chunk_index = cursor / self.chunk_size;
let chunk_offset = (cursor % self.chunk_size) as usize;
let chunk = self.chunks.get(&chunk_index)?;
if chunk_offset >= chunk.len() {
return None;
}
let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
cursor += take as u64;
remaining -= take;
if take == 0 {
return None;
}
}
Some(out)
}
fn ensure_chunks(&mut self, first: u64, last: u64, requested_end: u64) -> Result<(), MdfError> {
// Walk [first..=last], find each contiguous run of missing chunks,
// issue one read per run.
let mut idx = first;
while idx <= last {
if self.chunks.contains_key(&idx) {
idx += 1;
continue;
}
let run_start = idx;
while idx <= last && !self.chunks.contains_key(&idx) {
idx += 1;
}
let run_end = idx - 1;
let read_offset = run_start * self.chunk_size;
let mut read_len = (run_end - run_start + 1) * self.chunk_size;
// Clamp against the known end of the resource: strict inner
// readers reject reads past EOF, and the final chunk is allowed
// to be short.
if let Some(size) = self.known_size {
if read_offset >= size {
for slot in run_start..=run_end {
self.chunks.insert(slot, Vec::new());
}
continue;
}
read_len = read_len.min(size - read_offset);
}
let bytes = match self.inner.read_range(read_offset, read_len) {
Ok(b) => {
self.underlying_requests += 1;
b
}
Err(e) => {
self.underlying_requests += 1;
// The whole-chunk read may extend past EOF (the resource
// size need not be a multiple of chunk_size). Learn the
// true end from the error when it reports one, otherwise
// fall back to the span the caller actually asked for,
// and retry clamped.
let clamp_to = match &e {
MdfError::TooShortBuffer { actual, .. }
if (*actual as u64) > read_offset
&& (*actual as u64) < read_offset + read_len =>
{
self.known_size = Some(*actual as u64);
*actual as u64
}
_ if requested_end > read_offset
&& requested_end < read_offset + read_len =>
{
requested_end
}
_ => return Err(e),
};
let b = self.inner.read_range(read_offset, clamp_to - read_offset)?;
self.underlying_requests += 1;
b
}
};
// Split the response into chunk-sized pieces. The last chunk
// may be short if the file ends partway through it.
for (i, slot) in (run_start..=run_end).enumerate() {
let start = i * self.chunk_size as usize;
if start >= bytes.len() {
self.chunks.insert(slot, Vec::new());
continue;
}
let end = std::cmp::min(start + self.chunk_size as usize, bytes.len());
self.chunks.insert(slot, bytes[start..end].to_vec());
}
}
Ok(())
}
}
impl<R: ByteRangeReader<Error = MdfError>> ByteRangeReader for CachingRangeReader<R> {
type Error = MdfError;
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
if length == 0 {
return Ok(Vec::new());
}
if self.bypass {
// Serve from already-cached chunks when possible (e.g. a small
// conversion block lazily resolved at read time that lands in a
// metadata chunk fetched during the index walk); otherwise forward
// the (typically large data-block) read straight through.
if let Some(bytes) = self.try_serve_from_cache(offset, length) {
self.cache_hits += 1;
return Ok(bytes);
}
let bytes = self.inner.read_range(offset, length)?;
self.underlying_requests += 1;
return Ok(bytes);
}
let first = offset / self.chunk_size;
let last = (offset + length - 1) / self.chunk_size;
let read_end = offset + length;
// A chunk cached from an earlier EOF-clamped read may be shorter than
// the span this read needs from it. Drop such chunks so ensure_chunks
// refetches them (clamped to this read's span or the known size).
for i in first..=last {
if let Some(chunk) = self.chunks.get(&i) {
let chunk_start = i * self.chunk_size;
let cached_end = chunk_start + chunk.len() as u64;
let mut needed_end = read_end.min(chunk_start + self.chunk_size);
if let Some(size) = self.known_size {
needed_end = needed_end.min(size);
}
if cached_end < needed_end {
self.chunks.remove(&i);
}
}
}
// Track cache-hit metric only when no underlying read is required.
let need_fetch = (first..=last).any(|i| !self.chunks.contains_key(&i));
self.ensure_chunks(first, last, read_end)?;
if !need_fetch {
self.cache_hits += 1;
}
// Capacity capped so a forged huge length cannot abort on allocation.
let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
let mut remaining = length as usize;
let mut cursor = offset;
while remaining > 0 {
let chunk_index = cursor / self.chunk_size;
let chunk_offset = (cursor % self.chunk_size) as usize;
let chunk = self.chunks.get(&chunk_index).expect("chunk fetched above");
if chunk_offset >= chunk.len() {
return Err(MdfError::TooShortBuffer {
actual: chunk.len(),
expected: chunk_offset + 1,
file: file!(),
line: line!(),
});
}
let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
cursor += take as u64;
remaining -= take;
if take == 0 {
break;
}
}
if out.len() != length as usize {
return Err(MdfError::TooShortBuffer {
actual: out.len(),
expected: length as usize,
file: file!(),
line: line!(),
});
}
Ok(out)
}
}
/// HTTP range-request reader using the synchronous [`ureq`] client.
///
/// Each [`ByteRangeReader::read_range`] call issues a single
/// `Range: bytes=A-B` GET request and expects an HTTP 206 response. The
/// underlying `ureq::Agent` is reused across calls so TCP keep-alive applies.
///
/// Wrap this in [`CachingRangeReader`] when building an index, otherwise the
/// many small metadata reads will each become a separate round-trip.
#[cfg(feature = "http")]
pub struct HttpRangeReader {
agent: ureq::Agent,
url: String,
request_count: u64,
}
#[cfg(feature = "http")]
impl HttpRangeReader {
pub fn new(url: impl Into<String>) -> Result<Self, MdfError> {
// ureq's native-tls feature is not auto-wired (unlike rustls): the
// connector must be constructed and attached explicitly, otherwise
// HTTPS requests fail with "no TLS backend is configured".
let connector = native_tls::TlsConnector::new().map_err(|e| {
MdfError::BlockSerializationError(format!("failed to init TLS backend: {e}"))
})?;
let agent = ureq::AgentBuilder::new()
.tls_connector(std::sync::Arc::new(connector))
.build();
Ok(Self {
agent,
url: url.into(),
request_count: 0,
})
}
/// Download the whole resource with one plain `GET`.
pub(crate) fn fetch_all(&mut self) -> Result<Vec<u8>, MdfError> {
use std::io::Read;
self.request_count += 1;
let response = self.agent.get(&self.url).call().map_err(|e| {
MdfError::BlockSerializationError(format!("HTTP request failed: {e}"))
})?;
let mut body = Vec::new();
response.into_reader().read_to_end(&mut body).map_err(MdfError::IOError)?;
Ok(body)
}
/// Learn the resource's total size with a single-byte ranged GET.
///
/// Uses `GET` with `Range: bytes=0-0` and parses the total length out of
/// the `Content-Range: bytes 0-0/<total>` header, rather than issuing a
/// `HEAD`. Presigned URLs (e.g. AWS S3) are signed for one specific HTTP
/// method, so a `HEAD` against a GET-signed URL is rejected with 403; a
/// ranged `GET` matches the method the data reads use.
pub fn probe_size(&mut self) -> Result<u64, MdfError> {
use std::io::Read;
let resp = self
.agent
.get(&self.url)
.set("Range", "bytes=0-0")
.call()
.map_err(|e| MdfError::BlockSerializationError(format!("HTTP GET error: {e}")))?;
self.request_count += 1;
// Preferred: total size from the Content-Range header of a 206 response.
let total = resp
.header("Content-Range")
.and_then(|cr| cr.rsplit('/').next().map(|s| s.trim().to_string()))
.filter(|s| s != "*")
.and_then(|s| s.parse::<u64>().ok());
// Fallback: a server that ignores the Range header replies 200 with the
// full body, in which case Content-Length is the total size. Drain the
// body so the connection can be reused for keep-alive.
let content_length = resp
.header("Content-Length")
.and_then(|s| s.parse::<u64>().ok());
let status = resp.status();
let mut sink = Vec::new();
let _ = resp.into_reader().take(1).read_to_end(&mut sink);
if let Some(len) = total {
Ok(len)
} else if status == 200 {
content_length.ok_or_else(|| {
MdfError::BlockSerializationError(
"size probe: server ignored Range and sent no Content-Length".into(),
)
})
} else {
Err(MdfError::BlockSerializationError(
"size probe: 206 response missing Content-Range total".into(),
))
}
}
/// Total number of HTTP requests issued by this reader.
pub fn request_count(&self) -> u64 {
self.request_count
}
}
#[cfg(feature = "http")]
impl ByteRangeReader for HttpRangeReader {
type Error = MdfError;
fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
use std::io::Read;
if length == 0 {
return Ok(Vec::new());
}
let range_header = format!("bytes={}-{}", offset, offset + length - 1);
let resp = self
.agent
.get(&self.url)
.set("Range", &range_header)
.call()
.map_err(|e| MdfError::BlockSerializationError(format!("HTTP GET error: {e}")))?;
self.request_count += 1;
// 206 Partial Content is the accepted path. A 200 means the server
// ignored the Range header and sent the whole resource: that is only
// usable when the requested range starts at offset 0 (the body can be
// truncated to `length`); for any other offset the first `length`
// bytes would silently come from the wrong position, so error out.
let status = resp.status();
match status {
206 => {}
200 => {
if offset != 0 {
return Err(MdfError::BlockSerializationError(format!(
"HTTP server ignored Range request (status 200) for offset {}; \
refusing to return bytes from the wrong position",
offset
)));
}
}
other => {
return Err(MdfError::BlockSerializationError(format!(
"HTTP range request returned unexpected status {other}"
)));
}
}
// Read at most `length` bytes (a 200 response carries the whole
// resource and must be truncated), then insist we actually received
// all of them: a short body must be an error, not silently fewer
// records. Capacity is capped so a forged huge length cannot abort
// on allocation.
let mut buf = Vec::with_capacity(length.min(1 << 20) as usize);
resp.into_reader()
.take(length)
.read_to_end(&mut buf)
.map_err(MdfError::IOError)?;
if (buf.len() as u64) < length {
// Report absolute positions so wrappers (e.g. CachingRangeReader)
// can learn the resource's true end from `actual`.
return Err(MdfError::TooShortBuffer {
actual: (offset + buf.len() as u64) as usize,
expected: (offset + length) as usize,
file: file!(),
line: line!(),
});
}
Ok(buf)
}
}
impl MdfIndex {
/// Create an index from an MDF file on disk.
///
/// Not available on `wasm32-unknown-unknown`; use [`from_bytes`](Self::from_bytes) instead.
#[cfg(not(target_arch = "wasm32"))]
pub fn from_file(file_path: &str) -> Result<Self, MdfError> {
let mdf = Mdf::from_file(file_path)?;
let file_size = std::fs::metadata(file_path)
.map_err(MdfError::IOError)?
.len();
let mut index = Self::build_index(mdf, file_size)?;
index.source = Some(Source::File(file_path.to_string()));
Ok(index)
}
/// Build an index from an MDF file served over HTTP / S3 using range
/// requests, remembering the URL as the index's [`Source`].
///
/// Only metadata blocks are fetched while building; sample data is read
/// lazily on [`MdfIndex::read`]. Requires the `http` feature.
#[cfg(feature = "http")]
pub fn from_url(url: &str) -> Result<Self, MdfError> {
Self::from_url_with_chunk_size(url, 1 << 20)
}
/// [`MdfIndex::from_url`] with an explicit metadata read-ahead chunk size.
#[cfg(feature = "http")]
pub fn from_url_with_chunk_size(url: &str, chunk_size: u64) -> Result<Self, MdfError> {
let mut http = HttpRangeReader::new(url)?;
let file_size = http.probe_size()?;
let mut cached = CachingRangeReader::with_chunk_size(http, chunk_size);
cached.set_known_size(file_size);
let mut index = Self::from_range_reader(&mut cached, file_size)?;
index.source = Some(Source::Url(url.to_string()));
Ok(index)
}
/// Shared index-building logic operating on an already-parsed [`MDF`].
fn build_index(mdf: Mdf, file_size: u64) -> Result<Self, MdfError> {
let start_time_ns = mdf.start_time_ns();
let mut indexed_groups = Vec::new();
// (own ##CG address, remote master ##CG address) per group.
let mut cg_links: Vec<(u64, u64)> = Vec::new();
for group in mdf.channel_groups() {
let raw_cg = group.raw_channel_group();
cg_links.push((raw_cg.addr, raw_cg.block.master_cg_addr));
// Unsorted data groups (a record-ID prefix with several channel
// groups sharing the same data blocks) would make every CG index
// the same interleaved records as if they were all its own.
let raw_dg = group.raw_data_group();
if raw_dg.block.record_id_len > 0 && raw_dg.channel_groups.len() > 1 {
return Err(MdfError::BlockSerializationError(
"unsorted data groups (record IDs with multiple channel groups) \
are not supported by the index"
.to_string(),
));
}
let mut indexed_channels = Vec::new();
let mmap = group.mmap();
for channel in group.channels() {
let block = channel.block();
let resolved_conversion = if let Some(mut conversion) = block.conversion.clone() {
if let Err(e) = conversion.resolve_all_dependencies(mmap) {
eprintln!("Warning: Failed to resolve conversion dependencies for channel '{}': {}",
block.name.as_deref().unwrap_or("<unnamed>"), e);
}
Some(conversion)
} else {
None
};
let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
let mut slice_reader = BorrowedSliceReader { data: mmap };
Self::extract_vlsd_data_blocks(&mut slice_reader, block.data)?
} else {
Vec::new()
};
indexed_channels.push(IndexedChannel {
name: channel.name()?,
unit: channel.unit()?,
comment: channel.comment()?,
data_type: block.data_type.clone(),
byte_offset: block.byte_offset,
bit_offset: block.bit_offset,
bit_count: block.bit_count,
channel_type: block.channel_type,
flags: block.flags,
pos_invalidation_bit: block.pos_invalidation_bit,
conversion: resolved_conversion,
conversion_addr: block.conversion_addr,
vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
Some(block.data)
} else {
None
},
vlsd_data_blocks,
});
}
let data_blocks = Self::extract_data_blocks(&group)?;
indexed_groups.push(IndexedChannelGroup {
name: group.name()?,
comment: group.comment()?,
record_id_len: group.raw_data_group().block.record_id_len,
record_size: group.raw_channel_group().block.samples_byte_nr,
invalidation_bytes: group.raw_channel_group().block.invalidation_bytes_nr,
record_count: group.raw_channel_group().block.cycles_nr,
channels: indexed_channels,
data_blocks,
master_group: None,
});
}
Self::link_remote_masters(&mut indexed_groups, &cg_links);
Ok(MdfIndex { file_size, start_time_ns, channel_groups: indexed_groups, source: None })
}
/// Fill [`IndexedChannelGroup::master_group`] for groups without a local
/// master whose `##CG` carries an MDF 4.2 remote-master link.
fn link_remote_masters(groups: &mut [IndexedChannelGroup], cg_links: &[(u64, u64)]) {
for g in 0..groups.len() {
let target = cg_links[g].1;
if target == 0 || groups[g].master_channel().is_some() {
continue;
}
groups[g].master_group = cg_links
.iter()
.position(|&(addr, _)| addr == target)
.filter(|&m| m != g && groups[m].master_channel().is_some());
}
}
/// Extract data block information from a channel group
fn extract_data_blocks(group: &crate::api::channel_group::ChannelGroup) -> Result<Vec<DataBlockInfo>, MdfError> {
let mut data_blocks = Vec::new();
let raw_data_group = group.raw_data_group();
let mmap = group.mmap();
// Start at the group's primary data pointer
let mut current_block_address = raw_data_group.block.data_block_addr;
while current_block_address != 0 {
let byte_offset = current_block_address as usize;
// Read the block header
let block_header = crate::blocks::common::BlockHeader::from_bytes(&mmap[byte_offset..byte_offset + 24])?;
match block_header.id.as_str() {
"##DT" | "##DV" => {
// Single contiguous DataBlock
let data_block_info = DataBlockInfo {
file_offset: current_block_address,
size: block_header.block_len,
is_compressed: false,
};
data_blocks.push(data_block_info);
// No list to follow, we're done
current_block_address = 0;
}
"##DZ" => {
// Compressed data block
let data_block_info = DataBlockInfo {
file_offset: current_block_address,
size: block_header.block_len,
is_compressed: true,
};
data_blocks.push(data_block_info);
current_block_address = 0;
}
"##DL" => {
// Fragmented list of data blocks
let data_list_block = crate::blocks::data_list_block::DataListBlock::from_bytes(&mmap[byte_offset..])?;
// Parse each fragment in this list
for &fragment_address in &data_list_block.data_links {
let fragment_offset = fragment_address as usize;
let fragment_header = crate::blocks::common::BlockHeader::from_bytes(&mmap[fragment_offset..fragment_offset + 24])?;
let is_compressed = fragment_header.id == "##DZ";
let data_block_info = DataBlockInfo {
file_offset: fragment_address,
size: fragment_header.block_len,
is_compressed,
};
data_blocks.push(data_block_info);
}
// Move to the next DLBLOCK in the chain (0 = end)
current_block_address = data_list_block.next;
}
unexpected_id => {
return Err(MdfError::BlockIDError {
actual: unexpected_id.to_string(),
expected: "##DT / ##DV / ##DL / ##DZ".to_string(),
});
}
}
}
Ok(data_blocks)
}
/// Create an index from an in-memory MDF byte buffer.
///
/// This is the primary constructor on `wasm32-unknown-unknown`.
pub fn from_bytes(data: Vec<u8>) -> Result<Self, MdfError> {
let file_size = data.len() as u64;
let mdf = Mdf::from_bytes(data)?;
Self::build_index(mdf, file_size)
}
/// Build an [`MdfIndex`] using only [`ByteRangeReader`] calls.
///
/// Issues range reads for the file's metadata structures (identification,
/// header, data groups, channel groups, channels, text and conversion
/// blocks, and data-block headers) but never reads the sample data
/// itself. Intended for remote sources such as HTTP-served files; wrap
/// the underlying reader in [`CachingRangeReader`] to keep the number of
/// underlying requests low.
///
/// `file_size` is stored on the resulting index for use by later byte-range
/// calculations. Callers should obtain it from a HEAD request (e.g.
/// [`HttpRangeReader::probe_size`]) or other out-of-band metadata.
pub fn from_range_reader<R>(
reader: &mut R,
file_size: u64,
) -> Result<Self, MdfError>
where
R: ByteRangeReader<Error = MdfError>,
{
use crate::parsing::reader_walk;
let walk = reader_walk::walk(reader)?;
let start_time_ns = if walk.header.abs_time == 0 {
None
} else {
Some(walk.header.abs_time)
};
let mut indexed_groups = Vec::with_capacity(walk.groups.len());
let cg_links: Vec<(u64, u64)> =
walk.groups.iter().map(|g| (g.cg_addr, g.cg.master_cg_addr)).collect();
for group in walk.groups {
let mut indexed_channels = Vec::with_capacity(group.channels.len());
for ch in group.channels {
let block = ch.block;
let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
Self::extract_vlsd_data_blocks(reader, block.data)?
} else {
Vec::new()
};
indexed_channels.push(IndexedChannel {
name: ch.name,
unit: ch.unit,
comment: ch.comment,
data_type: block.data_type.clone(),
byte_offset: block.byte_offset,
bit_offset: block.bit_offset,
bit_count: block.bit_count,
channel_type: block.channel_type,
flags: block.flags,
pos_invalidation_bit: block.pos_invalidation_bit,
// Remote / range-reader builds defer conversion resolution:
// only the block's location is recorded here; it is fetched
// and resolved lazily on the first value read.
conversion: None,
conversion_addr: ch.conversion_addr,
vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
Some(block.data)
} else {
None
},
vlsd_data_blocks,
});
}
// Bytes of record data the group holds, so equal-length ##DL
// lists can be sized without touching the data region.
let expected_bytes = group.cg.cycles_nr.checked_mul(
group.record_id_len as u64
+ group.cg.samples_byte_nr as u64
+ group.cg.invalidation_bytes_nr as u64,
);
let data_blocks = Self::extract_data_blocks_via_reader(
reader,
group.data_block_addr,
expected_bytes,
file_size,
)?;
indexed_groups.push(IndexedChannelGroup {
name: group.cg_name,
comment: group.cg_comment,
record_id_len: group.record_id_len,
record_size: group.cg.samples_byte_nr,
invalidation_bytes: group.cg.invalidation_bytes_nr,
record_count: group.cg.cycles_nr,
channels: indexed_channels,
data_blocks,
master_group: None,
});
}
Self::link_remote_masters(&mut indexed_groups, &cg_links);
Ok(MdfIndex {
file_size,
start_time_ns,
channel_groups: indexed_groups,
source: None,
})
}
/// Mirror of [`Self::extract_data_blocks`] that fetches headers via a
/// [`ByteRangeReader`] instead of slicing into a memory map.
///
/// When `reader.is_probing()` (an incremental gap-discovery pass — see
/// [`ByteRangeReader::is_probing`]), a failed read stops walking this
/// group's data-block chain and returns what was collected so far instead
/// of propagating the error: the reader has already recorded the miss, so
/// the caller can fetch it and retry. The resulting index is **partial**
/// and must be discarded while any reader miss remains — this is exactly
/// the batched gap-discovery contract `MdfIndex::from_range_reader`
/// callers (`buildIndexStep`/`IndexBuilder::step`) already enforce by only
/// reporting `done` once a pass records zero misses. On-demand readers
/// (the default `is_probing() == false`) are unaffected: a failed read is
/// still fatal, exactly as before.
///
/// For an **equal-length** `##DL` list (`dl_flags` bit 0) reached directly
/// from the data group, the fragment sizes follow from the list itself:
/// every fragment but the last holds `dl_equal_length` bytes and the last
/// holds the rest of `expected_bytes` (cycle count × record size). When
/// that arithmetic is consistent with the number of fragments and the file
/// size, the fragment headers are **not read** — on a column-oriented file
/// whose metadata sits at the front this keeps the whole index build inside
/// the metadata prefix (one or two requests, independent of the number of
/// data blocks). Reads still verify each fragment header they fetch. Any
/// inconsistency falls back to reading the headers.
fn extract_data_blocks_via_reader<R>(
reader: &mut R,
data_block_addr: u64,
expected_bytes: Option<u64>,
file_size: u64,
) -> Result<Vec<DataBlockInfo>, MdfError>
where
R: ByteRangeReader<Error = MdfError>,
{
let mut data_blocks = Vec::new();
// Read a range, but when probing and the read fails, stop walking
// this chain and hand back what's been collected so far rather than
// aborting the whole build.
macro_rules! probe_read {
($offset:expr, $len:expr) => {
match reader.read_range($offset, $len) {
Ok(b) => b,
Err(e) => {
if reader.is_probing() {
return Ok(data_blocks);
}
return Err(e);
}
}
};
}
let mut current_block_address = data_block_addr;
while current_block_address != 0 {
let header_bytes = probe_read!(current_block_address, 24);
let block_header =
crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;
match block_header.id.as_str() {
"##DT" | "##DV" => {
data_blocks.push(DataBlockInfo {
file_offset: current_block_address,
size: block_header.block_len,
is_compressed: false,
});
current_block_address = 0;
}
"##DZ" => {
data_blocks.push(DataBlockInfo {
file_offset: current_block_address,
size: block_header.block_len,
is_compressed: true,
});
current_block_address = 0;
}
"##DL" => {
let dl_bytes = probe_read!(current_block_address, block_header.block_len);
let data_list_block =
crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;
if current_block_address == data_block_addr && data_list_block.next == 0
&& let Some(derived) = Self::derive_equal_length_fragments(
&data_list_block,
expected_bytes,
file_size,
) {
data_blocks.extend(derived);
break;
}
for &fragment_address in &data_list_block.data_links {
let frag_header_bytes = probe_read!(fragment_address, 24);
let fragment_header = crate::blocks::common::BlockHeader::from_bytes(
&frag_header_bytes,
)?;
let is_compressed = fragment_header.id == "##DZ";
data_blocks.push(DataBlockInfo {
file_offset: fragment_address,
size: fragment_header.block_len,
is_compressed,
});
}
current_block_address = data_list_block.next;
}
unexpected_id => {
return Err(MdfError::BlockIDError {
actual: unexpected_id.to_string(),
expected: "##DT / ##DV / ##DL / ##DZ".to_string(),
});
}
}
}
Ok(data_blocks)
}
/// Fragment locations of an equal-length `##DL` derived without reading
/// the fragments (see [`Self::extract_data_blocks_via_reader`]); `None`
/// when the list is not equal-length or the numbers do not add up.
fn derive_equal_length_fragments(
dl: &crate::blocks::data_list_block::DataListBlock,
expected_bytes: Option<u64>,
file_size: u64,
) -> Option<Vec<DataBlockInfo>> {
let equal = dl.data_block_len.filter(|_| dl.flags & 1 != 0)?;
let total = expected_bytes?;
let n = dl.data_links.len() as u64;
if equal == 0 || n == 0 || total == 0 || dl.data_links.contains(&0) {
return None;
}
// (n-1) full fragments plus a non-empty last one must hold exactly `total`.
let full = (n - 1).checked_mul(equal)?;
if total <= full || total > full.checked_add(equal)? {
return None;
}
let last = total - full;
let mut out: Vec<DataBlockInfo> = Vec::with_capacity(n as usize);
for (i, &addr) in dl.data_links.iter().enumerate() {
let data = if i as u64 + 1 == n { last } else { equal };
let size = data.checked_add(24)?;
if file_size > 0 && addr.checked_add(size)? > file_size {
return None;
}
// Fragments must not overlap (ascending, each starting after the
// previous one ends); anything else is left to the headers.
if let Some(prev) = out.last()
&& addr < prev.file_offset.checked_add(prev.size)?
{
return None;
}
out.push(DataBlockInfo { file_offset: addr, size, is_compressed: false });
}
Some(out)
}
/// Read the data sections of `blocks` in order, coalescing blocks that sit
/// back to back in the file (at most 7 bytes of alignment padding apart)
/// into a single read of up to [`MAX_COALESCED_READ`] bytes, and call `f`
/// with each block's data section.
///
/// A column-oriented file stores each signal's blocks contiguously, so a
/// whole signal arrives in one range request instead of one per block.
/// Every read starts at a block header, and each block's header is
/// verified (`##DT`/`##DV`) before its data is decoded. The header's own
/// length is authoritative: when it disagrees with the indexed size (e.g.
/// fragment sizes derived from an equal-length `##DL` and a stale cycle
/// count), the block's real data section is used — re-read if it extends
/// beyond the coalesced read — so bytes beyond a block are never decoded.
fn for_each_data_section<R, F>(
reader: &mut R,
blocks: &[DataBlockInfo],
mut f: F,
) -> Result<(), MdfError>
where
R: ByteRangeReader<Error = MdfError>,
F: FnMut(&[u8]) -> Result<(), MdfError>,
{
let mut i = 0;
while i < blocks.len() {
let start = blocks[i].file_offset;
Self::data_section_size(&blocks[i])?;
let mut end = start.checked_add(blocks[i].size).ok_or_else(|| {
MdfError::BlockSerializationError("data block offset overflows".to_string())
})?;
let mut j = i + 1;
while j < blocks.len() {
let b = &blocks[j];
let b_end = b.file_offset.saturating_add(b.size);
if b.file_offset < end
|| b.file_offset - end > 7
|| b.size < 24
|| b_end - start > MAX_COALESCED_READ
{
break;
}
end = b_end;
j += 1;
}
let buf = reader.read_range(start, end - start)?;
for b in &blocks[i..j] {
let header_start = (b.file_offset - start) as usize;
let data_start = header_start + 24;
let len = Self::verified_data_len(buf.get(header_start..data_start), b)?;
match usize::try_from(len).ok().and_then(|l| buf.get(data_start..data_start.checked_add(l)?)) {
Some(data) => f(data)?,
None => f(&reader.read_range(b.file_offset + 24, len)?)?,
}
}
i = j;
}
Ok(())
}
/// Check that `header` (the 24 header bytes of `block`, if available) is an
/// uncompressed `##DT`/`##DV` block and return the length of its data
/// section according to the header (which wins over the indexed size).
fn verified_data_len(header: Option<&[u8]>, block: &DataBlockInfo) -> Result<u64, MdfError> {
let h = BlockHeader::from_bytes(header.unwrap_or(&[]))?;
if (h.id == "##DT" || h.id == "##DV") && h.block_len >= 24 {
return Ok(h.block_len - 24);
}
Err(MdfError::BlockSerializationError(format!(
"data block at offset {} is {} with length {} but the index expects an \
uncompressed ##DT/##DV block of {} bytes (compressed or inconsistent \
file; rebuild the index)",
block.file_offset, h.id, h.block_len, block.size
)))
}
/// Walk a VLSD channel's `data` chain (a single `##SD`, or a `##DL` chain
/// of `##SD`/`##DZ` fragments) and record each fragment's location in chain
/// order.
///
/// Generic over [`ByteRangeReader`] so the mmap path (via
/// [`BorrowedSliceReader`]) and the remote path share one implementation.
/// Cycle-detects the `##DL` `next` chain, rejects unexpected block IDs, and
/// validates that a variable-length `##DL`'s per-fragment virtual offsets
/// reproduce the running sum of prior fragments' data-section sizes — the
/// invariant the offset-based reader relies on.
///
/// When `reader.is_probing()`, a failed read stops walking this VLSD
/// chain and returns what was collected so far instead of propagating the
/// error — see the identical rationale on
/// [`Self::extract_data_blocks_via_reader`]. Non-probing readers keep
/// today's fatal-on-first-miss behavior.
fn extract_vlsd_data_blocks<R>(
reader: &mut R,
data_addr: u64,
) -> Result<Vec<DataBlockInfo>, MdfError>
where
R: ByteRangeReader<Error = MdfError>,
{
let mut data_blocks: Vec<DataBlockInfo> = Vec::new();
// See `extract_data_blocks_via_reader`'s `probe_read!` for the
// rationale: batched gap discovery skips an unreadable subtree
// instead of aborting the whole pass, but only when probing.
macro_rules! probe_read {
($offset:expr, $len:expr) => {
match reader.read_range($offset, $len) {
Ok(b) => b,
Err(e) => {
if reader.is_probing() {
return Ok(data_blocks);
}
return Err(e);
}
}
};
}
let mut visited: std::collections::HashSet<u64> = std::collections::HashSet::new();
// Running sum of fragment data-section sizes (size - 24), i.e. the
// virtual start offset of the next fragment in the concatenated stream.
let mut running_offset: u64 = 0;
let mut current = data_addr;
while current != 0 {
let header_bytes = probe_read!(current, 24);
let header = crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;
match header.id.as_str() {
"##SD" => {
data_blocks.push(DataBlockInfo {
file_offset: current,
size: header.block_len,
is_compressed: false,
});
current = 0;
}
"##DZ" => {
data_blocks.push(DataBlockInfo {
file_offset: current,
size: header.block_len,
is_compressed: true,
});
current = 0;
}
"##DL" => {
// Cycle detection on the DL chain: a chain revisiting an
// address would otherwise loop forever.
if !visited.insert(current) {
return Err(MdfError::BlockLinkError(format!(
"cycle detected in VLSD data list chain at address {:#x}",
current
)));
}
let dl_bytes = probe_read!(current, header.block_len);
let dl = crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;
for (i, &fragment_address) in dl.data_links.iter().enumerate() {
if fragment_address == 0 {
continue;
}
let frag_header_bytes = probe_read!(fragment_address, 24);
let frag_header =
crate::blocks::common::BlockHeader::from_bytes(&frag_header_bytes)?;
let is_compressed = match frag_header.id.as_str() {
"##SD" => false,
"##DZ" => true,
other => {
return Err(MdfError::BlockIDError {
actual: other.to_string(),
expected: "##SD / ##DZ".to_string(),
});
}
};
// A variable-length DL carries an explicit virtual
// offset per fragment. The offset-based read path maps
// an inline offset to a fragment via cumulative
// data-section sizes, so a non-contiguous chain would
// silently mislocate entries — reject it here.
if let Some(offsets) = &dl.offsets
&& let Some(&declared) = offsets.get(i)
&& declared != running_offset {
return Err(MdfError::BlockSerializationError(format!(
"non-contiguous VLSD ##SD chain is unsupported: \
fragment at offset {} declares virtual start {} \
but the running data-section sum is {}",
fragment_address, declared, running_offset
)));
}
let data_section = frag_header.block_len.checked_sub(24).ok_or_else(|| {
MdfError::BlockSerializationError(format!(
"VLSD fragment at offset {} has size {} \
(smaller than the 24-byte block header)",
fragment_address, frag_header.block_len
))
})?;
running_offset = running_offset.checked_add(data_section).ok_or_else(|| {
MdfError::BlockSerializationError(
"VLSD ##SD chain total size overflows the address space"
.to_string(),
)
})?;
data_blocks.push(DataBlockInfo {
file_offset: fragment_address,
size: frag_header.block_len,
is_compressed,
});
}
current = dl.next;
}
other => {
return Err(MdfError::BlockIDError {
actual: other.to_string(),
expected: "##SD / ##DL / ##DZ".to_string(),
});
}
}
}
Ok(data_blocks)
}
/// Save the index to a JSON file.
///
/// Not available on `wasm32-unknown-unknown`; use [`to_json`](Self::to_json) instead.
#[cfg(not(target_arch = "wasm32"))]
pub fn save(&self, index_path: &str) -> Result<(), MdfError> {
let json = self.to_json()?;
std::fs::write(index_path, json)
.map_err(MdfError::IOError)?;
Ok(())
}
/// Load an index from a JSON file.
///
/// Not available on `wasm32-unknown-unknown`; use [`from_json`](Self::from_json) instead.
#[cfg(not(target_arch = "wasm32"))]
pub fn load(index_path: &str) -> Result<Self, MdfError> {
let json = std::fs::read_to_string(index_path)
.map_err(MdfError::IOError)?;
Self::from_json(&json)
}
/// Serialize the index to a JSON string (available on all targets).
pub fn to_json(&self) -> Result<String, MdfError> {
serde_json::to_string_pretty(self)
.map_err(|e| MdfError::BlockSerializationError(format!("JSON serialization failed: {}", e)))
}
/// Deserialize an index from a JSON string (available on all targets).
///
/// The deserialized index is [validated](Self::validate) so hostile or
/// stale index data errors here instead of panicking later during reads.
pub fn from_json(json: &str) -> Result<Self, MdfError> {
let index: Self = serde_json::from_str(json)
.map_err(|e| MdfError::BlockSerializationError(format!("JSON deserialization failed: {}", e)))?;
index.validate()?;
Ok(index)
}
/// Validate structural invariants of the index.
///
/// Called from [`Self::from_json`] / [`Self::load`] so that
/// malformed (hostile or stale) index data returns an error instead of
/// causing panics, integer underflow, or huge allocations during reads.
pub fn validate(&self) -> Result<(), MdfError> {
for group in &self.channel_groups {
let group_name = group.name.as_deref().unwrap_or("<unnamed>");
for db in &group.data_blocks {
if db.size < 24 {
return Err(MdfError::BlockSerializationError(format!(
"invalid index: group '{}' data block at offset {} has size {} \
(smaller than the 24-byte block header)",
group_name, db.file_offset, db.size
)));
}
if db.file_offset.checked_add(db.size).is_none() {
return Err(MdfError::BlockSerializationError(format!(
"invalid index: group '{}' data block at offset {} with size {} \
overflows the file address space",
group_name, db.file_offset, db.size
)));
}
}
if !group.data_blocks.is_empty() {
Self::checked_record_size(group)?;
}
for channel in &group.channels {
for db in &channel.vlsd_data_blocks {
if db.size < 24 {
return Err(MdfError::BlockSerializationError(format!(
"invalid index: group '{}' VLSD data block at offset {} has size {} \
(smaller than the 24-byte block header)",
group_name, db.file_offset, db.size
)));
}
if db.file_offset.checked_add(db.size).is_none() {
return Err(MdfError::BlockSerializationError(format!(
"invalid index: group '{}' VLSD data block at offset {} with size {} \
overflows the file address space",
group_name, db.file_offset, db.size
)));
}
}
}
}
Ok(())
}
/// Total on-disk record size (record id + data + invalidation bytes) for
/// a group, validated non-zero so callers can safely divide by it.
fn checked_record_size(group: &IndexedChannelGroup) -> Result<usize, MdfError> {
let size = group.record_id_len as usize
+ group.record_size as usize
+ group.invalidation_bytes as usize;
if size == 0 {
return Err(MdfError::BlockSerializationError(format!(
"invalid index: channel group '{}' has record size 0",
group.name.as_deref().unwrap_or("<unnamed>")
)));
}
Ok(size)
}
/// Size of a data block's data section (block size minus the 24-byte
/// header), validated so a corrupt/forged block size cannot underflow.
fn data_section_size(data_block: &DataBlockInfo) -> Result<u64, MdfError> {
data_block.size.checked_sub(24).ok_or_else(|| {
MdfError::BlockSerializationError(format!(
"invalid index: data block at offset {} has size {} \
(smaller than the 24-byte block header)",
data_block.file_offset, data_block.size
))
})
}
/// Number of whole records in a data block's data section.
///
/// Errors if the block size underflows the header or if the data section
/// is not a multiple of the record size — a record spanning data-block
/// fragments is unsupported and silently flooring would decode garbage
/// for every record after the split.
fn records_in_block(data_block: &DataBlockInfo, record_size: usize) -> Result<u64, MdfError> {
let data_len = Self::data_section_size(data_block)?;
if data_len % record_size as u64 != 0 {
return Err(MdfError::BlockSerializationError(format!(
"data block at offset {}: data section of {} bytes is not a multiple of \
the {}-byte record — record spans data block fragments, which is unsupported",
data_block.file_offset, data_len, record_size
)));
}
Ok(data_len / record_size as u64)
}
/// Error for VLSD channels on the byte-range calculation paths.
///
/// A VLSD channel's fixed record field holds an 8-byte offset into a
/// separate `##SD` stream, not the value bytes, so a static
/// `(offset, length)` range cannot describe where a sample's payload
/// lives. Value reads (`read` / `values`) resolve the indirection and are
/// fully supported; only byte-range calculation refuses VLSD channels.
fn ensure_not_vlsd(channel: &IndexedChannel) -> Result<(), MdfError> {
if channel.channel_type == 1 {
return Err(MdfError::BlockSerializationError(format!(
"byte ranges cannot represent offset-indirected VLSD channel '{}'; \
use read()/values() instead",
channel.name.as_deref().unwrap_or("<unnamed>")
)));
}
Ok(())
}
/// Read channel values using the index and a byte range reader.
///
/// Internal positional helper — the public entry point is
/// [`MdfReader::values`], which resolves channels by name.
///
/// # Returns
/// A vector of `Option<DecodedValue>` where:
/// - `Some(value)` represents a valid decoded value
/// - `None` represents an invalid value (invalidation bit set or decoding failed)
pub(crate) fn read_channel_values<R: ByteRangeReader<Error = MdfError>>(
&self,
group_index: usize,
channel_index: usize,
reader: &mut R
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
let group = self.channel_groups.get(group_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
let channel = group.channels.get(channel_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
let conversion = Self::resolve_conversion(channel, reader)?;
if channel.is_virtual() {
return self.virtual_values(group, 0, group.record_count, conversion.as_ref());
}
if channel.channel_type == 1 {
return self.read_vlsd_channel_values(group, channel, conversion.as_ref(), reader);
}
// For regular channels, read from data blocks
self.read_regular_channel_values(group, channel, conversion.as_ref(), reader)
}
/// Values of a virtual channel (`cn_type` 3/6) for records
/// `[start, start + count)`: the raw value is the record index, converted
/// through the channel's conversion (MDF 4.1 §6.6.3).
fn virtual_values(
&self,
group: &IndexedChannelGroup,
start: u64,
count: u64,
conversion: Option<&ConversionBlock>,
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
// Nothing is read for a virtual channel, so bound the record count by
// stored data instead of trusting a possibly forged `record_count`:
// the group's own data blocks, or — for a byte-less time group (the
// virtual master `to_column_oriented` writes) — the largest
// data-backed group using it as its remote master.
let available = if !group.data_blocks.is_empty() {
Self::stored_records(group)?
} else {
let me = self.channel_groups.iter().position(|g| std::ptr::eq(g, group));
self.channel_groups
.iter()
.filter(|g| me.is_some() && g.master_group == me && !g.data_blocks.is_empty())
.filter_map(|g| Self::stored_records(g).ok())
.max()
// Nothing stored to check against: trust the group.
.unwrap_or(group.record_count)
};
match start.checked_add(count) {
Some(end) if end <= available => {}
_ => {
return Err(MdfError::BlockSerializationError(format!(
"virtual channel read of {} records from {} exceeds the {} records the \
group's data holds (rebuild the index)",
count, start, available
)))
}
}
let mut values = Vec::with_capacity((count as usize).min(1 << 24));
for i in start..start + count {
let raw = DecodedValue::UnsignedInteger(i);
values.push(Some(match conversion {
Some(conv) => conv.apply_decoded(raw, &[])?,
None => raw,
}));
}
Ok(values)
}
/// Read the samples of the channel at `(g, c)` for the record window
/// `[start, start + count)` only.
///
/// For a regular channel only the bytes of the window's records are read
/// (one range per data block the window touches, plus that block's
/// 24-byte header, which is verified). A VLSD channel is read in full and
/// sliced, since its payloads sit in a separate stream.
pub(crate) fn read_channel_values_window<R: ByteRangeReader<Error = MdfError>>(
&self,
g: usize,
c: usize,
start: u64,
count: u64,
reader: &mut R,
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
let (group, channel) = self.group_and_channel(g, c)?;
Self::check_window(group, start, count)?;
let conversion = Self::resolve_conversion(channel, reader)?;
self.window_values(group, channel, conversion.as_ref(), start, count, reader)
}
fn window_values<R: ByteRangeReader<Error = MdfError>>(
&self,
group: &IndexedChannelGroup,
channel: &IndexedChannel,
conversion: Option<&ConversionBlock>,
start: u64,
count: u64,
reader: &mut R,
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
if channel.is_virtual() {
return self.virtual_values(group, start, count, conversion);
}
if channel.channel_type == 1 {
let all = self.read_vlsd_channel_values(group, channel, conversion, reader)?;
return Ok(all.into_iter().skip(start as usize).take(count as usize).collect());
}
let record_size = Self::checked_record_size(group)?;
let temp_cb = channel.to_channel_block();
let mut values = Vec::with_capacity((count as usize).min(1 << 24));
Self::for_each_window_section(reader, group, record_size, start, count, |data| {
Self::decode_records_to_values(data, record_size, group, conversion, &temp_cb, &mut values)
})?;
Ok(values)
}
/// `f64` variant of [`window_values`](Self::window_values) (invalid or
/// non-numeric samples are NaN).
fn window_values_f64<R: ByteRangeReader<Error = MdfError>>(
&self,
group: &IndexedChannelGroup,
channel: &IndexedChannel,
conversion: Option<&ConversionBlock>,
start: u64,
count: u64,
reader: &mut R,
) -> Result<Vec<f64>, MdfError> {
if channel.is_virtual() || channel.channel_type == 1 {
let vals = self.window_values(group, channel, conversion, start, count, reader)?;
return Ok(Self::vlsd_values_to_f64(vals));
}
let record_size = Self::checked_record_size(group)?;
let temp_cb = channel.to_decode_only_channel_block();
let linear_coeffs = Self::get_linear_coeffs(conversion);
let mut values = Vec::with_capacity((count as usize).min(1 << 24));
Self::for_each_window_section(reader, group, record_size, start, count, |data| {
Self::decode_records_to_f64(data, record_size, group, channel, conversion, &temp_cb, linear_coeffs, conversion.is_some(), &mut values)
})?;
Ok(values)
}
/// Call `f` with the bytes of the records `[start, start + count)` of
/// `group`, one slice per data block the window touches.
fn for_each_window_section<R, F>(
reader: &mut R,
group: &IndexedChannelGroup,
record_size: usize,
start: u64,
count: u64,
mut f: F,
) -> Result<(), MdfError>
where
R: ByteRangeReader<Error = MdfError>,
F: FnMut(&[u8]) -> Result<(), MdfError>,
{
let end = start + count;
let mut block_start = 0u64;
// A probing reader (the wasm fragment driver) records every missing
// block of the window in one pass instead of stopping at the first.
let mut first_err = None;
for block in &group.data_blocks {
if block_start >= end {
break;
}
if block.is_compressed {
return Err(MdfError::BlockSerializationError(
"Compressed blocks not yet supported in index reader".to_string(),
));
}
let block_end = block_start + Self::records_in_block(block, record_size)?;
let (from, to) = (start.max(block_start), end.min(block_end));
if from < to {
let rel = (from - block_start) * record_size as u64;
let len = (to - from) * record_size as u64;
// Verify the block header like the full read path does (the
// header wins over the index): a window starting at the
// block's first record reads header and data in one request.
let read = if rel == 0 {
reader.read_range(block.file_offset, 24 + len).map(|mut bytes| {
let data = bytes.split_off(24.min(bytes.len()));
(bytes, data)
})
} else {
let header = reader.read_range(block.file_offset, 24);
let data = reader.read_range(block.file_offset + 24 + rel, len);
header.and_then(|h| data.map(|d| (h, d)))
};
match read {
Ok((header, data)) if first_err.is_none() => {
let real_len = Self::verified_data_len(Some(&header), block)?;
if rel + len > real_len {
return Err(MdfError::BlockSerializationError(format!(
"data block at offset {} holds {} data bytes but the index \
expects at least {} (inconsistent file; rebuild the index)",
block.file_offset, real_len, rel + len
)));
}
f(&data)?
}
Ok(_) => {}
Err(e) if reader.is_probing() => {
first_err.get_or_insert(e);
}
Err(e) => return Err(e),
}
}
block_start = block_end;
}
if let Some(e) = first_err {
return Err(e);
}
if block_start < end {
return Err(MdfError::BlockSerializationError(format!(
"record window ending at {} exceeds the {} records held by the data blocks",
end, block_start
)));
}
Ok(())
}
/// Records held by a group's data blocks.
fn stored_records(group: &IndexedChannelGroup) -> Result<u64, MdfError> {
let record_size = Self::checked_record_size(group)?;
let mut total = 0u64;
for block in &group.data_blocks {
total = total.saturating_add(Self::records_in_block(block, record_size)?);
}
Ok(total)
}
fn group_and_channel(&self, g: usize, c: usize) -> Result<(&IndexedChannelGroup, &IndexedChannel), MdfError> {
let group = self.channel_groups.get(g)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
let channel = group.channels.get(c)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
Ok((group, channel))
}
fn check_window(group: &IndexedChannelGroup, start: u64, count: u64) -> Result<(), MdfError> {
match start.checked_add(count) {
Some(end) if end <= group.record_count => Ok(()),
_ => Err(MdfError::BlockSerializationError(format!(
"record window starting at {} for {} records exceeds the group's {} records",
start, count, group.record_count
))),
}
}
/// `(group, channel)` of the time axis for `(g, c)`: its master, or the
/// channel itself when it *is* the master.
fn time_axis_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
match self.master_location(g, c) {
Some(m) => Some(m),
None => self.channel_groups.get(g)?.channels.get(c)?.is_master().then_some((g, c)),
}
}
/// Record window `(start, count)` of the group owning `(g, c)` whose
/// master (time) values lie in `[t_start, t_end]` (either bound optional).
///
/// The master must be non-decreasing, as MDF requires for a time master.
/// It is searched rather than read: each step reads [`TIME_SEARCH_FANOUT`]
/// single records, so a window is found in a handful of small reads
/// (`log16(records)` rounds per bound). With a probing reader (the wasm
/// fragment driver) both bounds' probes of a round are attempted before the
/// first miss is returned, so every gap of the round is recorded at once.
pub(crate) fn record_window_for_time<R: ByteRangeReader<Error = MdfError>>(
&self,
g: usize,
c: usize,
t_start: Option<f64>,
t_end: Option<f64>,
reader: &mut R,
) -> Result<(u64, u64), MdfError> {
let (group, channel) = self.group_and_channel(g, c)?;
let Some((mg, m)) = self.time_axis_location(g, c) else {
// Same rule as the in-memory reader (`types::slice_signal`): an
// empty group selects nothing, otherwise a master is required.
if group.record_count == 0 {
return Ok((0, 0));
}
return Err(MdfError::InvalidArgument(format!(
"channel '{}' has no master (time) channel; cannot select by time",
channel.name.as_deref().unwrap_or_default()
)));
};
let (mgroup, mchannel) = self.group_and_channel(mg, m)?;
let n = group.record_count.min(mgroup.record_count);
let conversion = Self::resolve_conversion(mchannel, reader)?;
let probe = |i: u64, reader: &mut R| -> Result<f64, MdfError> {
Ok(self.window_values_f64(mgroup, mchannel, conversion.as_ref(), i, 1, reader)?[0])
};
// first record with t >= t_start; first record with t > t_end
let mut lo = Bound::new(n);
let mut hi = Bound::new(n);
if t_start.is_none() {
lo.done_at(0);
}
if t_end.is_none() {
hi.done_at(n);
}
while !(lo.done() && hi.done()) {
let mut first_err = None;
for (bound, below) in [
(&mut lo, &(|v: f64| t_start.is_some_and(|t| v < t)) as &dyn Fn(f64) -> bool),
(&mut hi, &|v: f64| t_end.is_some_and(|t| v <= t)),
] {
if bound.done() {
continue;
}
let probes = bound.probes();
let mut below_flags = Vec::with_capacity(probes.len());
for &p in &probes {
match probe(p, reader) {
Ok(v) => below_flags.push(below(v)),
Err(e) => {
first_err.get_or_insert(e);
}
}
}
if below_flags.len() == probes.len() {
bound.narrow(&probes, &below_flags);
}
}
if let Some(e) = first_err {
return Err(e);
}
}
let (start, end) = (lo.lo, hi.lo.max(lo.lo));
Ok((start, end - start))
}
/// Resolve a channel's conversion for reading.
///
/// Prefers a conversion already resolved into the index (local-file /
/// in-memory builds, and older serialized indexes). Otherwise — the remote
/// / range-reader build path, which records only
/// [`IndexedChannel::conversion_addr`] — it fetches the `##CC` block and
/// resolves its dependency chain through `reader`, exactly when the caller
/// asks to read values. Returns `None` when the channel has no conversion.
fn resolve_conversion<R: ByteRangeReader<Error = MdfError>>(
channel: &IndexedChannel,
reader: &mut R,
) -> Result<Option<ConversionBlock>, MdfError> {
if let Some(conv) = &channel.conversion {
return Ok(Some(conv.clone()));
}
if channel.conversion_addr == 0 {
return Ok(None);
}
let addr = channel.conversion_addr;
let header_bytes = reader.read_range(addr, 24)?;
let header = BlockHeader::from_bytes(&header_bytes)?;
if header.id != "##CC" {
return Err(MdfError::BlockIDError {
actual: header.id,
expected: "##CC".to_string(),
});
}
let full = reader.read_range(addr, header.block_len)?;
let mut cc = ConversionBlock::from_bytes(&full)?;
cc.resolve_all_dependencies_via_reader(reader, addr)?;
Ok(Some(cc))
}
/// Resolve the conversion of the channel at `(g, c)` using `reader`,
/// following the same lazy rules as the read paths. Crate-visible so the
/// wasm bindings can drive fragment-based conversion resolution: pointing a
/// gap-reporting reader at this lets the JS side discover exactly which
/// conversion-block byte ranges it must fetch before a fragment read.
#[allow(dead_code)] // used by the wasm bindings (wasm feature)
pub(crate) fn resolve_channel_conversion<R: ByteRangeReader<Error = MdfError>>(
&self,
g: usize,
c: usize,
reader: &mut R,
) -> Result<Option<ConversionBlock>, MdfError> {
let channel = self
.channel_groups
.get(g)
.and_then(|grp| grp.channels.get(c))
.ok_or_else(|| {
MdfError::BlockSerializationError("Invalid channel index".to_string())
})?;
Self::resolve_conversion(channel, reader)
}
/// Extract linear conversion coefficients (a, b) for inline application.
fn get_linear_coeffs(conversion: Option<&ConversionBlock>) -> Option<(f64, f64)> {
conversion.and_then(|conv| {
if conv.cc_type == ConversionType::Linear && conv.cc_val.len() >= 2 {
Some((conv.cc_val[0], conv.cc_val[1]))
} else {
None
}
})
}
/// Read values for a regular (non-VLSD) channel using byte range reader
fn read_regular_channel_values<R: ByteRangeReader<Error = MdfError>>(
&self,
group: &IndexedChannelGroup,
channel: &IndexedChannel,
conversion: Option<&ConversionBlock>,
reader: &mut R,
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
let record_size = Self::checked_record_size(group)?;
let mut total_records: usize = 0;
for data_block in &group.data_blocks {
if data_block.is_compressed {
return Err(MdfError::BlockSerializationError(
"Compressed blocks not yet supported in index reader".to_string()
));
}
total_records += Self::records_in_block(data_block, record_size)? as usize;
}
// Cap the pre-allocation: `total_records` derives from index-supplied
// block sizes, and a forged value must not abort on allocation. The
// vector still grows as needed; real reads fail earlier at the reader.
let mut values = Vec::with_capacity(total_records.min(1 << 24));
let temp_cb = channel.to_channel_block();
Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
Self::decode_records_to_values(block_data, record_size, group, conversion, &temp_cb, &mut values)
})?;
Ok(values)
}
/// Read values for a VLSD channel (channel type 1) via a byte-range reader.
///
/// The channel's fixed record field holds an 8-byte little-endian virtual
/// offset into the concatenation of the `##SD` fragments' data sections;
/// at that offset lives one `[u32 length][payload]` entry. This resolves
/// each record's offset into the captured fragment chain and decodes the
/// payload, preserving one value per record so [`Signal`] timestamps stay
/// aligned and per-record invalidation can be honoured.
fn read_vlsd_channel_values<R: ByteRangeReader<Error = MdfError>>(
&self,
group: &IndexedChannelGroup,
channel: &IndexedChannel,
conversion: Option<&ConversionBlock>,
reader: &mut R,
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
// Compressed fragments (either the fixed records or the SD stream) are
// not decodable yet.
if group.data_blocks.iter().any(|b| b.is_compressed)
|| channel.vlsd_data_blocks.iter().any(|b| b.is_compressed)
{
return Err(MdfError::BlockSerializationError(
"Compressed blocks not yet supported in index reader".to_string(),
));
}
// A VLSD channel without a data link has no signal data at all —
// rebuilding the index cannot help, so distinguish it from an index
// built before VLSD chains were captured.
if channel.vlsd_data_blocks.is_empty() {
if channel.vlsd_data_address.is_none() {
return Err(MdfError::BlockSerializationError(format!(
"VLSD channel '{}' has no signal data (its ##SD data link is 0)",
channel.name.as_deref().unwrap_or("<unnamed>")
)));
}
return Err(MdfError::BlockSerializationError(format!(
"VLSD channel '{}' has no signal-data fragments recorded in the index; \
rebuild the index with this version to read it",
channel.name.as_deref().unwrap_or("<unnamed>")
)));
}
// The VLSD offset field is fixed at 64 bits by the spec and is
// byte-aligned; a nonzero bit offset would silently shift every
// resolved stream offset.
if channel.bit_count != 64 || channel.bit_offset != 0 {
return Err(MdfError::BlockSerializationError(format!(
"VLSD channel '{}' has a {}-bit record field at bit offset {}; the \
inline VLSD offset must be a byte-aligned 64-bit field",
channel.name.as_deref().unwrap_or("<unnamed>"),
channel.bit_count,
channel.bit_offset
)));
}
// Fetch each SD fragment's data section, tracking each fragment's
// virtual start offset in the concatenated stream.
let mut fragments: Vec<Vec<u8>> = Vec::with_capacity(channel.vlsd_data_blocks.len());
let mut frag_starts: Vec<u64> = Vec::with_capacity(channel.vlsd_data_blocks.len());
let mut running: u64 = 0;
for db in &channel.vlsd_data_blocks {
let data_len = Self::data_section_size(db)?;
let bytes = reader.read_range(db.file_offset + 24, data_len)?;
frag_starts.push(running);
running = running.checked_add(bytes.len() as u64).ok_or_else(|| {
MdfError::BlockSerializationError(
"VLSD ##SD chain total size overflows the address space".to_string(),
)
})?;
fragments.push(bytes);
}
let stream_len = running;
let record_size = Self::checked_record_size(group)?;
let record_id_len = group.record_id_len as usize;
let cg_data_bytes = group.record_size;
let has_invalidation = group.invalidation_bytes > 0;
let all_invalid = channel.flags & 0x1 != 0;
let offset_pos = record_id_len + channel.byte_offset as usize;
// A fixed-record channel block (data == 0) drives the validity check;
// a separate VLSD block (data != 0) drives payload decoding.
let validity_cb = channel.to_channel_block();
let mut payload_cb = channel.to_channel_block();
payload_cb.data = 1;
let mut total_records: usize = 0;
for data_block in &group.data_blocks {
total_records += Self::records_in_block(data_block, record_size)? as usize;
}
let mut values = Vec::with_capacity(total_records.min(1 << 24));
Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
if block_data.len() % record_size != 0 {
return Err(MdfError::BlockSerializationError(format!(
"data block length {} is not a multiple of the {}-byte record — \
record spans data block fragments, which is unsupported",
block_data.len(),
record_size
)));
}
let record_count = block_data.len() / record_size;
for i in 0..record_count {
let record = &block_data[i * record_size..(i + 1) * record_size];
if all_invalid
|| (has_invalidation
&& !check_value_validity(record, record_id_len, cg_data_bytes, &validity_cb))
{
values.push(None);
continue;
}
// Read the inline 8-byte virtual offset.
if offset_pos + 8 > record.len() {
return Err(MdfError::TooShortBuffer {
actual: record.len(),
expected: offset_pos + 8,
file: file!(),
line: line!(),
});
}
let virtual_offset =
u64::from_le_bytes(record[offset_pos..offset_pos + 8].try_into().unwrap());
if virtual_offset >= stream_len {
return Err(MdfError::BlockSerializationError(format!(
"VLSD inline offset {} is past the end of the {}-byte signal-data stream",
virtual_offset, stream_len
)));
}
// Locate the fragment whose virtual span contains the offset.
let frag_idx = frag_starts.partition_point(|&s| s <= virtual_offset) - 1;
let frag = &fragments[frag_idx];
let pos = (virtual_offset - frag_starts[frag_idx]) as usize;
if pos + 4 > frag.len() {
return Err(MdfError::BlockSerializationError(format!(
"VLSD entry at virtual offset {} is truncated: no room for its \
length prefix in fragment {}",
virtual_offset, frag_idx
)));
}
let len = u32::from_le_bytes(frag[pos..pos + 4].try_into().unwrap()) as usize;
let start = pos + 4;
let end = match start.checked_add(len) {
Some(e) if e <= frag.len() => e,
_ => {
return Err(MdfError::BlockSerializationError(format!(
"VLSD entry at virtual offset {} declares length {} which \
exceeds fragment {} (size {})",
virtual_offset, len, frag_idx, frag.len()
)));
}
};
let payload = &frag[start..end];
if let Some(value) = decode_channel_value(payload, 0, &payload_cb) {
let final_value = if let Some(conversion) = conversion {
conversion.apply_decoded(value, &[])?
} else {
value
};
values.push(Some(final_value));
} else {
values.push(None);
}
}
Ok(())
})?;
Ok(values)
}
/// Map VLSD decoded values to `f64`, matching `Channel::values`:
/// numeric variants convert, everything else (strings, bytes, invalid) is
/// NaN.
fn vlsd_values_to_f64(values: Vec<Option<DecodedValue>>) -> Vec<f64> {
values
.into_iter()
.map(|v| match v {
Some(DecodedValue::Float(f)) => f,
Some(DecodedValue::UnsignedInteger(u)) => u as f64,
Some(DecodedValue::SignedInteger(i)) => i as f64,
_ => f64::NAN,
})
.collect()
}
/// Decode records from a data block slice into values vec.
/// Shared by both the reader-based and slice-based paths.
fn decode_records_to_values(
block_data: &[u8],
record_size: usize,
group: &IndexedChannelGroup,
conversion: Option<&ConversionBlock>,
temp_cb: &crate::blocks::channel_block::ChannelBlock,
values: &mut Vec<Option<DecodedValue>>,
) -> Result<(), MdfError> {
if record_size == 0 {
return Err(MdfError::BlockSerializationError(
"invalid index: record size is 0".to_string(),
));
}
if !block_data.len().is_multiple_of(record_size) {
return Err(MdfError::BlockSerializationError(format!(
"data block length {} is not a multiple of the {}-byte record — \
record spans data block fragments, which is unsupported",
block_data.len(),
record_size
)));
}
let record_count = block_data.len() / record_size;
let record_id_len = group.record_id_len as usize;
let cg_data_bytes = group.record_size;
for i in 0..record_count {
let record = &block_data[i * record_size..(i + 1) * record_size];
if let Some(decoded) = decode_channel_value_with_validity(
record, record_id_len, cg_data_bytes, temp_cb,
) {
if decoded.is_valid {
let final_value = if let Some(conversion) = conversion {
conversion.apply_decoded(decoded.value, &[])?
} else {
decoded.value
};
values.push(Some(final_value));
} else {
values.push(None);
}
} else {
values.push(None);
}
}
Ok(())
}
/// Decode records from a data block as f64 values.
/// Uses the fast decode_f64_from_record path and applies conversions inline.
/// For channels without invalidation bytes, skips validity checking entirely.
fn decode_records_to_f64(
block_data: &[u8],
record_size: usize,
group: &IndexedChannelGroup,
channel: &IndexedChannel,
conversion: Option<&ConversionBlock>,
temp_cb: &crate::blocks::channel_block::ChannelBlock,
linear_coeffs: Option<(f64, f64)>,
has_conversion: bool,
values: &mut Vec<f64>,
) -> Result<(), MdfError> {
if record_size == 0 {
return Err(MdfError::BlockSerializationError(
"invalid index: record size is 0".to_string(),
));
}
if !block_data.len().is_multiple_of(record_size) {
return Err(MdfError::BlockSerializationError(format!(
"data block length {} is not a multiple of the {}-byte record — \
record spans data block fragments, which is unsupported",
block_data.len(),
record_size
)));
}
let record_count = block_data.len() / record_size;
let record_id_len = group.record_id_len as usize;
let cg_data_bytes = group.record_size;
let has_invalidation = group.invalidation_bytes > 0;
// MDF 4.1: cn_flags bit 0 ("all values invalid") applies regardless
// of whether the group carries invalidation bytes. Short-circuit to
// NaN for every sample, matching decode_records_to_values.
if channel.flags & 0x1 != 0 {
values.extend(std::iter::repeat_n(f64::NAN, record_count));
return Ok(());
}
if !has_invalidation && !has_conversion {
// Fastest path: no invalidation, no conversion - just decode f64 directly
for i in 0..record_count {
let record = &block_data[i * record_size..(i + 1) * record_size];
values.push(decode_f64_from_record(record, record_id_len, temp_cb));
}
} else if !has_invalidation && linear_coeffs.is_some() {
// Fast path: no invalidation, linear conversion
let (a, b) = linear_coeffs.unwrap();
for i in 0..record_count {
let record = &block_data[i * record_size..(i + 1) * record_size];
let raw = decode_f64_from_record(record, record_id_len, temp_cb);
values.push(a + b * raw);
}
} else if !has_invalidation {
// No invalidation but non-linear conversion - need full decode for conversion
for i in 0..record_count {
let record = &block_data[i * record_size..(i + 1) * record_size];
let raw = decode_f64_from_record(record, record_id_len, temp_cb);
if let Some(coeffs) = linear_coeffs {
values.push(coeffs.0 + coeffs.1 * raw);
} else if has_conversion {
// Need to decode via DecodedValue for complex conversions
if let Some(decoded) = decode_channel_value_with_validity(
record, record_id_len, cg_data_bytes, temp_cb,
) {
match conversion.unwrap().apply_decoded(decoded.value, &[])? {
DecodedValue::Float(v) => values.push(v),
DecodedValue::UnsignedInteger(v) => values.push(v as f64),
DecodedValue::SignedInteger(v) => values.push(v as f64),
_ => values.push(f64::NAN),
}
} else {
values.push(f64::NAN);
}
} else {
values.push(raw);
}
}
} else {
// Has invalidation bytes - must check validity
for i in 0..record_count {
let record = &block_data[i * record_size..(i + 1) * record_size];
let is_valid = check_value_validity(record, record_id_len, cg_data_bytes, temp_cb);
if is_valid {
let raw = decode_f64_from_record(record, record_id_len, temp_cb);
if let Some((a, b)) = linear_coeffs {
values.push(a + b * raw);
} else if has_conversion {
if let Some(decoded) = decode_channel_value_with_validity(
record, record_id_len, cg_data_bytes, temp_cb,
) {
match conversion.unwrap().apply_decoded(decoded.value, &[])? {
DecodedValue::Float(v) => values.push(v),
DecodedValue::UnsignedInteger(v) => values.push(v as f64),
DecodedValue::SignedInteger(v) => values.push(v as f64),
_ => values.push(f64::NAN),
}
} else {
values.push(f64::NAN);
}
} else {
values.push(raw);
}
} else {
values.push(f64::NAN);
}
}
}
Ok(())
}
// ----- metadata (cross-language contract) -----------------------------
/// Metadata of every channel group, in file order.
///
/// The raw indexed structures (record layout, data-block locations) are
/// available through the public [`channel_groups`](Self::channel_groups)
/// field.
pub fn groups(&self) -> Result<Vec<GroupInfo>, MdfError> {
Ok((0..self.channel_groups.len()).map(|g| self.group_info(g)).collect())
}
/// Metadata of the first channel group named `name`, or `None`.
pub fn group(&self, name: &str) -> Result<Option<GroupInfo>, MdfError> {
Ok(self
.channel_groups
.iter()
.position(|g| g.name.as_deref() == Some(name))
.map(|g| self.group_info(g)))
}
/// Metadata of the first channel named `name`, or `None`. Pass `group` to
/// look only in the group(s) with that name.
pub fn channel(&self, name: &str, group: Option<&str>) -> Result<Option<ChannelInfo>, MdfError> {
Ok(self.indexed_channel(name, group).map(IndexedChannel::info))
}
/// Names of every named channel across all groups (duplicates kept).
pub fn channel_names(&self) -> Result<Vec<String>, MdfError> {
Ok(self
.channel_groups
.iter()
.flat_map(|g| g.channels.iter())
.filter_map(|c| c.name.clone())
.collect())
}
/// Measurement start time in nanoseconds since the Unix epoch, or `None`
/// if the file header does not record one.
pub fn start_time_ns(&self) -> Option<u64> {
self.start_time_ns
}
/// Size in bytes of the indexed MDF file.
pub fn file_size(&self) -> u64 {
self.file_size
}
/// The raw [`IndexedChannel`] of the first channel named `name` (in the
/// group(s) named `group`, when given). Rust-only access to the record
/// layout behind [`channel`](Self::channel).
pub fn indexed_channel(&self, name: &str, group: Option<&str>) -> Option<&IndexedChannel> {
let (g, c) = self.locate_opt(name, group)?;
self.channel_groups.get(g)?.channels.get(c)
}
fn group_info(&self, g: usize) -> GroupInfo {
let group = &self.channel_groups[g];
GroupInfo {
name: group.name.clone(),
comment: group.comment.clone(),
record_count: group.record_count,
channel_names: group.channels.iter().filter_map(|c| c.name.clone()).collect(),
// A column-oriented (MDF 4.2) signal group reports the shared
// time channel it references.
master_channel: group
.master_channel()
.or_else(|| {
group
.master_group
.and_then(|mg| self.channel_groups.get(mg))
.and_then(|mg| mg.master_channel())
})
.and_then(|c| c.name.clone()),
channels: group.channels.iter().map(IndexedChannel::info).collect(),
}
}
/// Position of a channel by name, optionally restricted to a group name.
pub(crate) fn locate_opt(&self, name: &str, group: Option<&str>) -> Option<(usize, usize)> {
match group {
Some(group) => self.locate_in(group, name),
None => self.locate(name),
}
}
/// [`locate_opt`](Self::locate_opt), erroring with `ChannelNotFound`.
pub(crate) fn locate_checked(&self, name: &str, group: Option<&str>) -> Result<(usize, usize), MdfError> {
self.locate_opt(name, group)
.ok_or_else(|| MdfError::channel_not_found(name, group))
}
/// Resolve a channel name to its `(group_index, channel_index)` position.
///
/// Returns the first match across all groups. Internal helper backing the
/// name-based public methods.
pub(crate) fn locate(&self, name: &str) -> Option<(usize, usize)> {
for (g, group) in self.channel_groups.iter().enumerate() {
for (c, channel) in group.channels.iter().enumerate() {
if channel.name.as_deref() == Some(name) {
return Some((g, c));
}
}
}
None
}
/// Resolve a `(group name, channel name)` pair to indices.
///
/// Every group carrying that name is searched (a column-oriented file has
/// one channel group per signal, all named after the source group).
pub(crate) fn locate_in(&self, group: &str, name: &str) -> Option<(usize, usize)> {
self.channel_groups
.iter()
.enumerate()
.filter(|(_, grp)| grp.name.as_deref() == Some(group))
.find_map(|(g, grp)| {
grp.channels
.iter()
.position(|ch| ch.name.as_deref() == Some(name))
.map(|c| (g, c))
})
}
/// `(group, channel)` of the master (time) channel for the channel at
/// `(g, c)`: the group's own master, or the remote master of an MDF 4.2
/// column-oriented group. `None` when there is none or `(g, c)` is itself
/// the master.
pub(crate) fn master_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
let grp = self.channel_groups.get(g)?;
if let Some(m) = grp.channels.iter().position(|ch| ch.is_master()) {
return (m != c).then_some((g, m));
}
let mg = grp.master_group?;
let m = self.channel_groups.get(mg)?.channels.iter().position(|ch| ch.is_master())?;
Some((mg, m))
}
/// Bind this index to a byte-range source for reading sample data.
///
/// The returned [`MdfReader`] borrows the index and owns `reader`; read
/// values by channel name without re-supplying the source each time.
pub fn open<R: ByteRangeReader<Error = MdfError>>(&self, reader: R) -> MdfReader<'_, R> {
MdfReader { index: self, reader }
}
/// Bind this index to a local file (via memory map) for reading.
///
/// Convenience wrapper around [`MdfIndex::open`] using [`MmapRangeReader`].
/// Not available on `wasm32-unknown-unknown`.
#[cfg(not(target_arch = "wasm32"))]
pub fn open_file(&self, path: &str) -> Result<MdfReader<'_, MmapRangeReader>, MdfError> {
Ok(self.open(MmapRangeReader::new(path)?))
}
/// The data source `read` / `values` fetch sample bytes from, if any.
pub fn source(&self) -> Option<&Source> {
self.source.as_ref()
}
/// Attach (or replace) the data source used by `read` / `values`.
///
/// Accepts a [`Source`] or a string: `http(s)://` URLs are read with range
/// requests (with the `http` feature), anything else is a file path.
pub fn set_source(&mut self, source: impl Into<Source>) {
self.source = Some(source.into());
}
/// Detach the data source.
pub fn clear_source(&mut self) {
self.source = None;
}
// ----- data (cross-language contract) ---------------------------------
/// Read a channel as a [`Signal`]: its values (conversions applied,
/// `None` = invalid sample) paired with the group's time axis. For the
/// master channel itself `timestamps` is empty.
///
/// This is the lazy read path: bytes are fetched from the attached
/// [`Source`] now, not at index build time. Errors with
/// [`MdfError::ChannelNotFound`] if no such channel exists, or if no
/// source is attached (see [`set_source`](Self::set_source)).
///
/// `options` is `None` for the whole channel, or a [`ReadOptions`] with a
/// group filter and/or a time or record window. A window fetches only the
/// selected records: a time window is located by searching the master
/// channel (a few single-record reads), not by downloading it.
pub fn read<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
let default = ReadOptions::default();
let options = options.into().unwrap_or(&default);
let window = options.window()?;
let (g, c) = self.locate_checked(name, options.group_name())?;
if window == Window::All {
return self.read_signal(g, c);
}
let mut reader = self.source_reader(g, c)?;
let (start, count) = self.resolve_window(g, c, window, &mut reader)?;
read_signal_window(self, g, c, start, count, &mut reader)
}
/// Read a numeric channel as plain `f64` values (no timestamps).
/// Conversions are applied; invalid and non-numeric samples are `NaN`.
/// `options` as for [`read`](Self::read).
pub fn values<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
let default = ReadOptions::default();
let options = options.into().unwrap_or(&default);
let window = options.window()?;
let (g, c) = self.locate_checked(name, options.group_name())?;
if window == Window::All {
return self.read_values_f64_via_source(g, c);
}
let mut reader = self.source_reader(g, c)?;
let (start, count) = self.resolve_window(g, c, window, &mut reader)?;
self.values_f64_window(g, c, start, count, &mut reader)
}
/// First and last master (time) value of the group holding `name`, or
/// `None` for an empty group. Reads just two records. Errors if the group
/// has no master channel.
pub fn time_range(&self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
let (g, c) = self.locate_checked(name, group)?;
let mut reader = self.source_reader(g, c)?;
self.time_range_at(g, c, &mut reader)
}
/// The conversion `read` / `values` apply to channel `name`, fully
/// resolved, or `None` when the channel has none.
///
/// Indexes built over the network record only a conversion's location;
/// it is then fetched through the attached source on demand.
pub fn conversion(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionInfo>, MdfError> {
Ok(self.conversion_block(name, group)?.as_ref().map(ConversionInfo::from))
}
/// Records `[start, start + count)` a window selects in the group of `(g, c)`.
pub(crate) fn resolve_window<R: ByteRangeReader<Error = MdfError>>(
&self,
g: usize,
c: usize,
window: Window,
reader: &mut R,
) -> Result<(u64, u64), MdfError> {
let total = self.channel_groups[g].record_count;
match window {
Window::All => Ok((0, total)),
Window::Records(start, count) => resolve_records(start, count, total),
Window::Time(t_start, t_end) => self.record_window_for_time(g, c, t_start, t_end, reader),
}
}
/// `f64` values of records `[start, start + count)` of `(g, c)`.
pub(crate) fn values_f64_window<R: ByteRangeReader<Error = MdfError>>(
&self,
g: usize,
c: usize,
start: u64,
count: u64,
reader: &mut R,
) -> Result<Vec<f64>, MdfError> {
Ok(self
.read_channel_values_window(g, c, start, count, reader)?
.iter()
.map(decoded_opt_to_f64)
.collect())
}
/// First and last value of the time axis of `(g, c)` (two single-record reads).
pub(crate) fn time_range_at<R: ByteRangeReader<Error = MdfError>>(
&self,
g: usize,
c: usize,
reader: &mut R,
) -> Result<Option<TimeRange>, MdfError> {
let total = self.channel_groups[g].record_count;
let Some((mg, m)) = self.time_axis_location(g, c) else {
if total == 0 {
return Ok(None);
}
let name = self.channel_groups[g].channels[c].name.clone().unwrap_or_default();
return Err(MdfError::InvalidArgument(format!(
"channel '{name}' has no master (time) channel"
)));
};
let n = total.min(self.channel_groups[mg].record_count);
if n == 0 {
return Ok(None);
}
let first = self.values_f64_window(mg, m, 0, 1, reader);
// Attempt the second read even when the first failed, so a probing
// reader records both gaps in one pass.
let last = self.values_f64_window(mg, m, n - 1, 1, reader)?;
Ok(Some(TimeRange { start: first?[0], end: last[0] }))
}
/// A byte-range reader over the attached source, with the conversion of
/// `(g, c)` resolved up front for URL sources.
fn source_reader(&self, g: usize, c: usize) -> Result<SourceReader, MdfError> {
let _ = (g, c);
match self.require_source()? {
#[cfg(not(target_arch = "wasm32"))]
Source::File(path) => Ok(SourceReader::File(MmapRangeReader::new(path)?)),
#[cfg(target_arch = "wasm32")]
Source::File(_) => Err(MdfError::BlockSerializationError(
"file sources are not available on wasm32".to_string(),
)),
#[cfg(feature = "http")]
Source::Url(url) => {
let http = HttpRangeReader::new(url)?;
Ok(SourceReader::Url(self.url_reader_with_conversion(http, g, c)?))
}
}
}
/// Decode a channel + its group master from the attached source.
fn read_signal(&self, g: usize, c: usize) -> Result<Signal, MdfError> {
let channel = &self.channel_groups[g].channels[c];
let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
let values = self.read_values_via_source(g, c)?;
let timestamps = match self.master_location(g, c) {
Some((mg, m)) => self.read_values_f64_via_source(mg, m)?,
None => Vec::new(),
};
Ok(Signal { name, unit, timestamps, values })
}
/// Wrap `http` for a value read of `(g, c)`: a deferred conversion is
/// fetched first through a small (64 KiB) read-ahead cache — the `##CC`
/// block and the text/conversion blocks it references usually sit next to
/// each other, so this costs one request instead of one per block — then
/// the cache switches to bypass mode so the bulk data is streamed directly
/// (cached conversion bytes are still served from memory).
#[cfg(feature = "http")]
fn url_reader_with_conversion(
&self,
http: HttpRangeReader,
g: usize,
c: usize,
) -> Result<CachingRangeReader<HttpRangeReader>, MdfError> {
let mut cached = CachingRangeReader::with_chunk_size(http, 64 * 1024);
if self.file_size > 0 {
cached.set_known_size(self.file_size);
}
let channel = &self.channel_groups[g].channels[c];
if channel.conversion.is_none() && channel.conversion_addr != 0 {
self.resolve_channel_conversion(g, c, &mut cached)?;
}
cached.set_bypass(true);
Ok(cached)
}
/// Resolve the attached [`Source`], erroring with a helpful message if none.
fn require_source(&self) -> Result<&Source, MdfError> {
let source = self.source.as_ref().ok_or_else(|| {
MdfError::BlockSerializationError(
"no data source attached to index; build with from_file/from_url or call set_source".to_string(),
)
})?;
#[cfg(not(feature = "http"))]
{
let Source::File(path) = source;
if path.starts_with("http://") || path.starts_with("https://") {
return Err(MdfError::InvalidArgument(format!(
"'{path}' is a URL, but mf4-rs was built without the `http` feature"
)));
}
}
Ok(source)
}
/// Read one channel's decoded values lazily through the attached source.
pub(crate) fn read_values_via_source(
&self,
g: usize,
c: usize,
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
#[cfg(target_arch = "wasm32")]
let _ = (g, c);
match self.require_source()? {
#[cfg(not(target_arch = "wasm32"))]
Source::File(path) => {
let file = std::fs::File::open(path).map_err(MdfError::IOError)?;
let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
self.read_channel_values_from_slice(g, c, &mmap)
}
#[cfg(target_arch = "wasm32")]
Source::File(_) => Err(MdfError::BlockSerializationError(
"file sources are not available on wasm32".to_string(),
)),
#[cfg(feature = "http")]
Source::Url(url) => {
let http = HttpRangeReader::new(url)?;
let mut cached = self.url_reader_with_conversion(http, g, c)?;
self.read_channel_values(g, c, &mut cached)
}
}
}
/// Resolve a channel's conversion, fetching it through the attached source
/// if it was not resolved at index-build time (the remote / range-reader
/// path records only its location — see [`IndexedChannel::conversion_addr`]).
///
/// Returns `None` when the channel has no conversion. Errors if resolution
/// needs the source (a deferred conversion) but none is attached — attach
/// one with [`set_source`](Self::set_source).
///
/// This returns the raw [`ConversionBlock`]; [`conversion`](Self::conversion)
/// is the contract method returning a plain [`ConversionInfo`].
pub fn conversion_block(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionBlock>, MdfError> {
let (g, c) = self.locate_checked(name, group)?;
let channel = &self.channel_groups[g].channels[c];
if let Some(conv) = &channel.conversion {
return Ok(Some(conv.clone()));
}
if channel.conversion_addr == 0 {
return Ok(None);
}
match self.require_source()? {
#[cfg(not(target_arch = "wasm32"))]
Source::File(path) => {
let file = std::fs::File::open(path).map_err(MdfError::IOError)?;
let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
let mut slice_reader = BorrowedSliceReader { data: &mmap };
Self::resolve_conversion(channel, &mut slice_reader)
}
#[cfg(target_arch = "wasm32")]
Source::File(_) => Err(MdfError::BlockSerializationError(
"file sources are not available on wasm32".to_string(),
)),
#[cfg(feature = "http")]
Source::Url(url) => {
let http = HttpRangeReader::new(url)?;
let mut cached = CachingRangeReader::new(http);
Self::resolve_conversion(channel, &mut cached)
}
}
}
/// Read one channel's values as `f64` lazily through the attached source.
pub(crate) fn read_values_f64_via_source(
&self,
g: usize,
c: usize,
) -> Result<Vec<f64>, MdfError> {
#[cfg(target_arch = "wasm32")]
let _ = (g, c);
match self.require_source()? {
#[cfg(not(target_arch = "wasm32"))]
Source::File(path) => {
let file = std::fs::File::open(path).map_err(MdfError::IOError)?;
let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
self.read_channel_values_from_slice_as_f64(g, c, &mmap)
}
#[cfg(target_arch = "wasm32")]
Source::File(_) => Err(MdfError::BlockSerializationError(
"file sources are not available on wasm32".to_string(),
)),
#[cfg(feature = "http")]
Source::Url(url) => {
let http = HttpRangeReader::new(url)?;
let mut cached = self.url_reader_with_conversion(http, g, c)?;
self.read_channel_values_as_f64(g, c, &mut cached)
}
}
}
/// Get the exact byte ranges needed to read all data for a specific channel
///
/// Returns a vector of (file_offset, length) tuples representing the byte ranges
/// that need to be read from the file to get all data for the specified channel.
///
/// # Arguments
/// * `group_index` - Index of the channel group
/// * `channel_index` - Index of the channel within the group
///
/// # Returns
/// * `Ok(Vec<(u64, u64)>)` - Vector of (offset, length) byte ranges
/// * `Err(MdfError)` - If indices are invalid or channel type not supported
pub(crate) fn get_channel_byte_ranges(
&self,
group_index: usize,
channel_index: usize,
) -> Result<Vec<(u64, u64)>, MdfError> {
let group = self.channel_groups.get(group_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
let channel = group.channels.get(channel_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
// VLSD channels not supported for byte range calculation
Self::ensure_not_vlsd(channel)?;
// For regular channels, calculate byte ranges from data blocks
self.calculate_regular_channel_byte_ranges(group, channel)
}
/// Get the exact byte ranges for a specific record range of a channel
///
/// This is useful when you only want to read a subset of records rather than all data.
///
/// # Arguments
/// * `group_index` - Index of the channel group
/// * `channel_index` - Index of the channel within the group
/// * `start_record` - Starting record index (0-based)
/// * `record_count` - Number of records to read
///
/// # Returns
/// * `Ok(Vec<(u64, u64)>)` - Vector of (offset, length) byte ranges
/// * `Err(MdfError)` - If indices are invalid, range is out of bounds, or channel type not supported
pub(crate) fn get_channel_byte_ranges_for_records(
&self,
group_index: usize,
channel_index: usize,
start_record: u64,
record_count: u64,
) -> Result<Vec<(u64, u64)>, MdfError> {
let group = self.channel_groups.get(group_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
let channel = group.channels.get(channel_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
// Validate record range with checked arithmetic (forged inputs must
// error, not wrap), and without underflowing when record_count == 0.
let end_record = start_record.checked_add(record_count).ok_or_else(|| {
MdfError::BlockSerializationError(format!(
"Record range overflow: start {} + count {}",
start_record, record_count
))
})?;
if end_record > group.record_count {
return Err(MdfError::BlockSerializationError(
format!("Record range starting at {} for {} records exceeds total records {}",
start_record, record_count, group.record_count)
));
}
// VLSD channels not supported for byte range calculation
Self::ensure_not_vlsd(channel)?;
self.calculate_channel_byte_ranges_for_records(group, channel, start_record, record_count)
}
/// Calculate byte ranges for a regular (non-VLSD) channel for all records
fn calculate_regular_channel_byte_ranges(
&self,
group: &IndexedChannelGroup,
channel: &IndexedChannel,
) -> Result<Vec<(u64, u64)>, MdfError> {
self.calculate_channel_byte_ranges_for_records(group, channel, 0, group.record_count)
}
/// Calculate byte ranges for a regular channel for a specific record range
fn calculate_channel_byte_ranges_for_records(
&self,
group: &IndexedChannelGroup,
channel: &IndexedChannel,
start_record: u64,
record_count: u64,
) -> Result<Vec<(u64, u64)>, MdfError> {
// Record structure: record_id + data_bytes + invalidation_bytes
let record_size = Self::checked_record_size(group)?;
let channel_offset_in_record = group.record_id_len as usize + channel.byte_offset as usize;
// Calculate how many bytes this channel needs per record
let channel_bytes_per_record = if matches!(channel.data_type,
DataType::StringLatin1 | DataType::StringUtf8 | DataType::StringUtf16LE |
DataType::StringUtf16BE | DataType::ByteArray | DataType::MimeSample | DataType::MimeStream)
{
channel.bit_count as usize / 8
} else {
(channel.bit_offset as usize + channel.bit_count as usize).div_ceil(8).max(1)
};
let mut byte_ranges = Vec::new();
let mut records_processed = 0u64;
for data_block in &group.data_blocks {
if data_block.is_compressed {
return Err(MdfError::BlockSerializationError(
"Compressed blocks not supported for byte range calculation".to_string()
));
}
let block_data_start = data_block.file_offset + 24; // Skip block header
let records_in_block = Self::records_in_block(data_block, record_size)?;
// Determine which records from this block we need
let block_start_record = records_processed;
let block_end_record = records_processed + records_in_block;
let need_start = start_record.max(block_start_record);
let need_end = (start_record + record_count).min(block_end_record);
if need_start < need_end {
// We need some records from this block
let first_record_in_block = need_start - block_start_record;
let last_record_in_block = need_end - block_start_record - 1;
// Calculate byte range for the channel data in these records
let first_channel_byte = block_data_start +
first_record_in_block * record_size as u64 +
channel_offset_in_record as u64;
let last_channel_byte = block_data_start +
last_record_in_block * record_size as u64 +
channel_offset_in_record as u64 +
channel_bytes_per_record as u64 - 1;
let range_length = last_channel_byte - first_channel_byte + 1;
byte_ranges.push((first_channel_byte, range_length));
}
records_processed = block_end_record;
// Early exit if we've processed all needed records
if records_processed >= start_record + record_count {
break;
}
}
Ok(byte_ranges)
}
/// Byte ranges occupied by a channel across the whole file, by name.
///
/// Each tuple is `(offset, length)`, accounting for the channel's position
/// in the record layout and any data-block splitting. Resolves the first
/// channel matching `name`. Power-user entry point for issuing HTTP-range
/// or S3 partial reads yourself.
///
/// Note: each returned range is one *coalesced* span per data-block
/// fragment, running from the first byte of the channel in the fragment's
/// first record to its last byte in the fragment's last record. Because
/// records interleave all channels of the group, the span **includes the
/// bytes of the other channels** lying between this channel's samples.
///
/// Pass `group` to resolve the channel in the group(s) with that name.
/// Refused for VLSD channels (use `read` / `values`).
pub fn byte_ranges(&self, name: &str, group: Option<&str>) -> Result<Vec<(u64, u64)>, MdfError> {
let (g, c) = self.locate_checked(name, group)?;
self.get_channel_byte_ranges(g, c)
}
/// Byte ranges for a record window of a channel, by name.
///
/// `start_record` is 0-based. Errors if `start_record + record_count`
/// exceeds the records available. Useful for paging through a large
/// channel. See [`MdfIndex::byte_ranges`] for what each returned span
/// covers.
pub fn byte_ranges_for_records(
&self,
name: &str,
start_record: u64,
record_count: u64,
group: Option<&str>,
) -> Result<Vec<(u64, u64)>, MdfError> {
let (g, c) = self.locate_checked(name, group)?;
self.get_channel_byte_ranges_for_records(g, c, start_record, record_count)
}
/// Fast path: read channel values as `Vec<f64>` using a byte range reader.
///
/// This avoids boxing `DecodedValue` enums and applies linear conversions inline.
/// For channels without invalidation bytes (the common case), validity checking
/// is skipped entirely. Invalid samples are represented as `f64::NAN`.
pub(crate) fn read_channel_values_as_f64<R: ByteRangeReader<Error = MdfError>>(
&self,
group_index: usize,
channel_index: usize,
reader: &mut R,
) -> Result<Vec<f64>, MdfError> {
let group = self.channel_groups.get(group_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
let channel = group.channels.get(channel_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
let conversion = Self::resolve_conversion(channel, reader)?;
if channel.is_virtual() {
let vals = self.virtual_values(group, 0, group.record_count, conversion.as_ref())?;
return Ok(Self::vlsd_values_to_f64(vals));
}
if channel.channel_type == 1 {
let vals = self.read_vlsd_channel_values(group, channel, conversion.as_ref(), reader)?;
return Ok(Self::vlsd_values_to_f64(vals));
}
let record_size = Self::checked_record_size(group)?;
let mut total_records: usize = 0;
for data_block in &group.data_blocks {
if data_block.is_compressed {
return Err(MdfError::BlockSerializationError(
"Compressed blocks not yet supported in index reader".to_string()
));
}
total_records += Self::records_in_block(data_block, record_size)? as usize;
}
// Cap the pre-allocation: `total_records` derives from index-supplied
// block sizes, and a forged value must not abort on allocation. The
// vector still grows as needed; real reads fail earlier at the reader.
let mut values = Vec::with_capacity(total_records.min(1 << 24));
let temp_cb = channel.to_decode_only_channel_block();
let linear_coeffs = Self::get_linear_coeffs(conversion.as_ref());
let has_conversion = conversion.is_some();
Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
Self::decode_records_to_f64(block_data, record_size, group, channel, conversion.as_ref(), &temp_cb, linear_coeffs, has_conversion, &mut values)
})?;
Ok(values)
}
/// Zero-copy fast path: read channel values directly from an `&[u8]` mmap slice.
///
/// Avoids all per-block heap allocation by slicing directly into the provided
/// memory-mapped region. This is the fastest `DecodedValue` read path when the
/// entire file is already mapped into memory.
#[allow(dead_code)] // used by the Python bindings (pyo3 feature)
pub(crate) fn read_channel_values_from_slice(
&self,
group_index: usize,
channel_index: usize,
file_data: &[u8],
) -> Result<Vec<Option<DecodedValue>>, MdfError> {
let group = self.channel_groups.get(group_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
let channel = group.channels.get(channel_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
let mut slice_reader = BorrowedSliceReader { data: file_data };
let conversion = Self::resolve_conversion(channel, &mut slice_reader)?;
if channel.is_virtual() {
return self.virtual_values(group, 0, group.record_count, conversion.as_ref());
}
if channel.channel_type == 1 {
return self.read_vlsd_channel_values(group, channel, conversion.as_ref(), &mut slice_reader);
}
let record_size = Self::checked_record_size(group)?;
let mut total_records: usize = 0;
for data_block in &group.data_blocks {
if data_block.is_compressed {
return Err(MdfError::BlockSerializationError(
"Compressed blocks not yet supported in index reader".to_string()
));
}
total_records += Self::records_in_block(data_block, record_size)? as usize;
}
// Cap the pre-allocation: `total_records` derives from index-supplied
// block sizes, and a forged value must not abort on allocation. The
// vector still grows as needed; real reads fail earlier at the reader.
let mut values = Vec::with_capacity(total_records.min(1 << 24));
let temp_cb = channel.to_channel_block();
for data_block in &group.data_blocks {
let block_data = Self::slice_data_block(file_data, data_block)?;
Self::decode_records_to_values(block_data, record_size, group, conversion.as_ref(), &temp_cb, &mut values)?;
}
Ok(values)
}
/// Zero-copy fast path: read channel values as `Vec<f64>` directly from an `&[u8]` mmap slice.
///
/// Combines zero-copy slice access with the f64 fast decode path. No per-block
/// allocation, no `DecodedValue` enum boxing. This is the fastest possible read
/// path. Invalid or undecodable samples are `f64::NAN`.
#[allow(dead_code)] // used by the Python bindings (pyo3 feature)
pub(crate) fn read_channel_values_from_slice_as_f64(
&self,
group_index: usize,
channel_index: usize,
file_data: &[u8],
) -> Result<Vec<f64>, MdfError> {
let group = self.channel_groups.get(group_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
let channel = group.channels.get(channel_index)
.ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
let mut slice_reader = BorrowedSliceReader { data: file_data };
let conversion = Self::resolve_conversion(channel, &mut slice_reader)?;
if channel.is_virtual() {
let vals = self.virtual_values(group, 0, group.record_count, conversion.as_ref())?;
return Ok(Self::vlsd_values_to_f64(vals));
}
if channel.channel_type == 1 {
let vals = self.read_vlsd_channel_values(group, channel, conversion.as_ref(), &mut slice_reader)?;
return Ok(Self::vlsd_values_to_f64(vals));
}
let record_size = Self::checked_record_size(group)?;
let mut total_records: usize = 0;
for data_block in &group.data_blocks {
if data_block.is_compressed {
return Err(MdfError::BlockSerializationError(
"Compressed blocks not yet supported in index reader".to_string()
));
}
total_records += Self::records_in_block(data_block, record_size)? as usize;
}
// Cap the pre-allocation: `total_records` derives from index-supplied
// block sizes, and a forged value must not abort on allocation. The
// vector still grows as needed; real reads fail earlier at the reader.
let mut values = Vec::with_capacity(total_records.min(1 << 24));
let temp_cb = channel.to_decode_only_channel_block();
let linear_coeffs = Self::get_linear_coeffs(conversion.as_ref());
let has_conversion = conversion.is_some();
for data_block in &group.data_blocks {
let block_data = Self::slice_data_block(file_data, data_block)?;
Self::decode_records_to_f64(block_data, record_size, group, channel, conversion.as_ref(), &temp_cb, linear_coeffs, has_conversion, &mut values)?;
}
Ok(values)
}
/// Slice a data block from file_data, skipping the 24-byte block header.
/// Uses checked arithmetic so a forged offset/size errors instead of
/// wrapping or panicking.
#[allow(dead_code)] // used by the Python bindings (pyo3 feature)
fn slice_data_block<'a>(file_data: &'a [u8], data_block: &DataBlockInfo) -> Result<&'a [u8], MdfError> {
Self::data_section_size(data_block)?;
let too_short = |expected: usize| MdfError::TooShortBuffer {
actual: file_data.len(),
expected,
file: file!(),
line: line!(),
};
let data_start = usize::try_from(data_block.file_offset)
.ok()
.and_then(|o| o.checked_add(24))
.ok_or_else(|| too_short(usize::MAX))?;
// The block header's own length wins over the indexed size.
let data_len = Self::verified_data_len(file_data.get(data_start - 24..data_start), data_block)?;
let data_end = usize::try_from(data_len)
.ok()
.and_then(|l| data_start.checked_add(l))
.ok_or_else(|| too_short(usize::MAX))?;
file_data.get(data_start..data_end).ok_or_else(|| too_short(data_end))
}
}
/// Records probed per round of the time search in
/// [`MdfIndex::record_window_for_time`].
const TIME_SEARCH_FANOUT: u64 = 16;
/// State of one partition-point search over `[lo, hi)`: the answer is the
/// first record for which the predicate ("still below the bound") is false.
struct Bound {
lo: u64,
hi: u64,
}
impl Bound {
fn new(n: u64) -> Self {
Bound { lo: 0, hi: n }
}
fn done(&self) -> bool {
self.lo >= self.hi
}
fn done_at(&mut self, at: u64) {
self.lo = at;
self.hi = at;
}
/// Up to [`TIME_SEARCH_FANOUT`] distinct, increasing records in `[lo, hi)`.
fn probes(&self) -> Vec<u64> {
let span = self.hi - self.lo;
if span <= TIME_SEARCH_FANOUT {
return (self.lo..self.hi).collect();
}
(0..TIME_SEARCH_FANOUT)
.map(|i| self.lo + (i as u128 * span as u128 / TIME_SEARCH_FANOUT as u128) as u64)
.collect()
}
/// Narrow to the gap between the last probe below the bound and the first
/// one not below it (values are non-decreasing).
fn narrow(&mut self, probes: &[u64], below: &[bool]) {
match below.iter().position(|b| !b) {
Some(0) => self.hi = probes[0],
Some(j) => {
self.lo = probes[j - 1] + 1;
self.hi = probes[j];
}
None => self.lo = probes[probes.len() - 1] + 1,
}
}
}
/// A reader bound to an [`MdfIndex`] and a single byte-range data source.
///
/// Obtained from [`MdfIndex::open`] / [`MdfIndex::open_file`]. The source is
/// supplied once; afterwards channels are read by name. Reads of the same
/// channel re-fetch from the underlying source, so cache or memory-map the
/// source (e.g. [`MmapRangeReader`], [`CachingRangeReader`]) when reading many
/// channels.
pub struct MdfReader<'a, R: ByteRangeReader<Error = MdfError>> {
index: &'a MdfIndex,
reader: R,
}
impl<'a, R: ByteRangeReader<Error = MdfError>> MdfReader<'a, R> {
/// The index this reader was opened against.
pub fn index(&self) -> &MdfIndex {
self.index
}
/// Mutable access to the underlying byte-range reader (e.g. to toggle
/// [`CachingRangeReader::set_bypass`] or inspect request counters).
pub fn reader_mut(&mut self) -> &mut R {
&mut self.reader
}
/// Consume the reader, returning the underlying byte-range source.
pub fn into_inner(self) -> R {
self.reader
}
/// Read a channel as a [`Signal`] — see [`MdfIndex::read`].
pub fn read<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
let default = ReadOptions::default();
let options = options.into().unwrap_or(&default);
let window = options.window()?;
let (g, c) = self.index.locate_checked(name, options.group_name())?;
if window == Window::All {
return self.read_signal(g, c);
}
let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
read_signal_window(self.index, g, c, start, count, &mut self.reader)
}
/// Read a numeric channel as plain `f64` values — see [`MdfIndex::values`].
pub fn values<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
let default = ReadOptions::default();
let options = options.into().unwrap_or(&default);
let window = options.window()?;
let (g, c) = self.index.locate_checked(name, options.group_name())?;
if window == Window::All {
return self.index.read_channel_values_as_f64(g, c, &mut self.reader);
}
let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
self.index.values_f64_window(g, c, start, count, &mut self.reader)
}
/// Rust-only: all samples of a channel as decoded values (no time axis),
/// keeping text and byte values that `values` would turn into `NaN`.
pub fn decoded_values(&mut self, name: &str, group: Option<&str>) -> Result<Vec<Option<DecodedValue>>, MdfError> {
let (g, c) = self.index.locate_checked(name, group)?;
self.index.read_channel_values(g, c, &mut self.reader)
}
/// First and last master (time) value of the group holding `name` — see
/// [`MdfIndex::time_range`].
pub fn time_range(&mut self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
let (g, c) = self.index.locate_checked(name, group)?;
self.index.time_range_at(g, c, &mut self.reader)
}
fn read_signal(&mut self, g: usize, c: usize) -> Result<Signal, MdfError> {
let channel = &self.index.channel_groups[g].channels[c];
let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
let values = self.index.read_channel_values(g, c, &mut self.reader)?;
let timestamps = match self.index.master_location(g, c) {
Some((mg, m)) => self
.index
.read_channel_values(mg, m, &mut self.reader)?
.iter()
.map(decoded_opt_to_f64)
.collect(),
None => Vec::new(),
};
Ok(Signal { name, unit, timestamps, values })
}
}
/// Window read shared by [`MdfReader`] and the wasm fragment driver: records
/// `[start, start + count)` of `(g, c)` paired with the same window of its
/// time axis.
pub(crate) fn read_signal_window<R: ByteRangeReader<Error = MdfError>>(
index: &MdfIndex,
g: usize,
c: usize,
start: u64,
count: u64,
reader: &mut R,
) -> Result<Signal, MdfError> {
let channel = &index.channel_groups[g].channels[c];
let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
let values = index.read_channel_values_window(g, c, start, count, reader);
// Read the master even when the values failed, so a probing reader
// records both gaps in one pass. Like a full read, the master itself
// carries no separate timestamps.
let timestamps = match index.master_location(g, c) {
Some((mg, m)) => index
.read_channel_values_window(mg, m, start, count, reader)?
.iter()
.map(decoded_opt_to_f64)
.collect(),
None => Vec::new(),
};
Ok(Signal { name, unit, timestamps, values: values? })
}