mf4-rs 3.0.0

mf4-rs is a Rust library for working with ASAM MDF 4 (Measurement Data Format) files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
//! 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, BlockParse};
use crate::blocks::conversion::{ConversionBlock, ConversionType};
use crate::error::MdfError;
use crate::parsing::decoder::{check_value_validity, decode_channel_value_with_validity, decode_f64_from_record, DecodedValue};
use crate::signal::{decoded_opt_to_f64, Signal};

/// 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>,
    /// 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)
    pub conversion: Option<ConversionBlock>,
    /// For VLSD channels: address of signal data blocks
    pub vlsd_data_address: Option<u64>,
}

impl IndexedChannel {
    /// `true` if this is the group's master channel (usually time).
    pub fn is_master(&self) -> bool {
        self.channel_type == 2
    }

    /// `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>,
}

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_from_file`]
/// re-attach one with [`MdfIndex::set_file`] / [`MdfIndex::set_url`]. 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),
}

/// 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_file` / `set_url`. 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>;
}

/// 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(|e| MdfError::IOError(e))?;
        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(|e| MdfError::IOError(e))?;

        let mut buffer = vec![0u8; length as usize];
        self.file.read_exact(&mut buffer)
            .map_err(|e| MdfError::IOError(e))?;

        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())
    }
}

/// 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,
        }
    }

    /// When set, every read forwards directly to the underlying reader.
    /// Use during value-read phases so large data-block fetches do not
    /// populate the cache.
    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(|_| ())
    }

    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 {
            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,
        })
    }

    /// 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`] 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(|e| MdfError::IOError(e))?
            .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);
        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();

        for group in mdf.channel_groups() {
            // 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
                };

                indexed_channels.push(IndexedChannel {
                    name: channel.name()?,
                    unit: channel.unit()?,
                    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,
                    vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
                        Some(block.data)
                    } else {
                        None
                    },
                });
            }

            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,
            });
        }

        Ok(MdfIndex { file_size, start_time_ns, channel_groups: indexed_groups, source: None })
    }

    /// 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());
        for group in walk.groups {
            let mut indexed_channels = Vec::with_capacity(group.channels.len());
            for ch in group.channels {
                let block = ch.block;
                indexed_channels.push(IndexedChannel {
                    name: ch.name,
                    unit: ch.unit,
                    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: ch.conversion,
                    vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
                        Some(block.data)
                    } else {
                        None
                    },
                });
            }

            let data_blocks =
                Self::extract_data_blocks_via_reader(reader, group.data_block_addr)?;

            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,
            });
        }

        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.
    fn extract_data_blocks_via_reader<R>(
        reader: &mut R,
        data_block_addr: u64,
    ) -> Result<Vec<DataBlockInfo>, MdfError>
    where
        R: ByteRangeReader<Error = MdfError>,
    {
        let mut data_blocks = Vec::new();
        let mut current_block_address = data_block_addr;

        while current_block_address != 0 {
            let header_bytes = reader.read_range(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 =
                        reader.read_range(current_block_address, block_header.block_len)?;
                    let data_list_block =
                        crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;

                    for &fragment_address in &data_list_block.data_links {
                        let frag_header_bytes = reader.read_range(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)
    }

    /// Save the index to a JSON file.
    ///
    /// Not available on `wasm32-unknown-unknown`; use [`to_json`] instead.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn save_to_file(&self, index_path: &str) -> Result<(), MdfError> {
        let json = self.to_json()?;
        std::fs::write(index_path, json)
            .map_err(|e| MdfError::IOError(e))?;
        Ok(())
    }

    /// Load an index from a JSON file.
    ///
    /// Not available on `wasm32-unknown-unknown`; use [`from_json`] instead.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn load_from_file(index_path: &str) -> Result<Self, MdfError> {
        let json = std::fs::read_to_string(index_path)
            .map_err(|e| MdfError::IOError(e))?;
        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_from_file`] 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)?;
            }
        }
        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 read paths that only handle fixed-size
    /// records. Triggers on `channel_type == 1` regardless of whether the SD
    /// address was captured: a VLSD channel without one is equally unreadable,
    /// and decoding the inline 8-byte SD offsets would return garbage.
    fn ensure_not_vlsd(channel: &IndexedChannel) -> Result<(), MdfError> {
        if channel.channel_type == 1 {
            return Err(MdfError::BlockSerializationError(format!(
                "VLSD channel '{}' not yet supported in index reader",
                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()))?;

        // VLSD channels are not supported: decoding their inline SD offsets
        // as payload would return garbage.
        Self::ensure_not_vlsd(channel)?;

        // For regular channels, read from data blocks
        self.read_regular_channel_values(group, channel, reader)
    }

    /// Extract linear conversion coefficients (a, b) for inline application.
    fn get_linear_coeffs(channel: &IndexedChannel) -> Option<(f64, f64)> {
        channel.conversion.as_ref().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,
        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();

        for data_block in &group.data_blocks {
            let block_data = reader
                .read_range(data_block.file_offset + 24, Self::data_section_size(data_block)?)?;
            Self::decode_records_to_values(&block_data, record_size, group, channel, &temp_cb, &mut values)?;
        }

        Ok(values)
    }

    /// 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,
        channel: &IndexedChannel,
        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() % 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;
        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) = &channel.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,
        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() % 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;
        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(f64::NAN).take(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 channel.conversion.as_ref().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 channel.conversion.as_ref().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(())
    }

    /// All channel groups in the file, in file order.
    pub fn groups(&self) -> &[IndexedChannelGroup] {
        &self.channel_groups
    }

    /// Find a channel group by its name.
    ///
    /// Returns the first group whose `##CG` acquisition name matches `name`.
    pub fn group(&self, name: &str) -> Option<&IndexedChannelGroup> {
        self.channel_groups
            .iter()
            .find(|g| g.name.as_deref() == Some(name))
    }

    /// Look up a single channel by name across all groups (first match).
    pub fn channel(&self, name: &str) -> Option<&IndexedChannel> {
        let (g, c) = self.locate(name)?;
        self.channel_groups.get(g)?.channels.get(c)
    }

    /// Look up a channel by group name + channel name.
    pub fn channel_in(&self, group: &str, name: &str) -> Option<&IndexedChannel> {
        self.group(group)?.channel(name)
    }

    /// The attached data source rendered as a string (file path or URL).
    pub fn source_string(&self) -> Option<String> {
        match &self.source {
            Some(Source::File(p)) => Some(p.clone()),
            #[cfg(feature = "http")]
            Some(Source::Url(u)) => Some(u.clone()),
            None => None,
        }
    }

    /// A flat catalog of every channel as `(source, group name, channel name)`.
    ///
    /// `source` is this index's attached source (the same value for every row,
    /// handy when concatenating catalogs from many files/URLs). Built purely
    /// from metadata — no sample data is read.
    pub fn signal_list(&self) -> Vec<(Option<String>, Option<String>, Option<String>)> {
        let src = self.source_string();
        let mut out = Vec::new();
        for group in &self.channel_groups {
            for channel in &group.channels {
                out.push((src.clone(), group.name.clone(), channel.name.clone()));
            }
        }
        out
    }

    /// Every channel name across all groups, in file order (duplicates kept).
    pub fn channel_names(&self) -> Vec<&str> {
        self.channel_groups
            .iter()
            .flat_map(|g| g.channels.iter())
            .filter_map(|c| c.name.as_deref())
            .collect()
    }

    /// 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.
    pub(crate) fn locate_in(&self, group: &str, name: &str) -> Option<(usize, usize)> {
        let g = self
            .channel_groups
            .iter()
            .position(|grp| grp.name.as_deref() == Some(group))?;
        let c = self.channel_groups[g]
            .channels
            .iter()
            .position(|ch| ch.name.as_deref() == Some(name))?;
        Some((g, c))
    }

    /// All `(group_index, channel_index)` positions matching a channel name.
    ///
    /// Useful when the same name appears in several groups (e.g. a per-group
    /// `Time` master channel).
    pub fn find_channels(&self, name: &str) -> Vec<(usize, usize)> {
        let mut matches = Vec::new();
        for (g, group) in self.channel_groups.iter().enumerate() {
            for (c, channel) in group.channels.iter().enumerate() {
                if channel.name.as_deref() == Some(name) {
                    matches.push((g, c));
                }
            }
        }
        matches
    }

    /// 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 attached to this index, if any.
    pub fn source(&self) -> Option<&Source> {
        self.source.as_ref()
    }

    /// Attach (or replace) the data source used by [`MdfIndex::read`].
    pub fn set_source(&mut self, source: Source) {
        self.source = Some(source);
    }

    /// Attach a local file path as the data source for lazy reads.
    pub fn set_file(&mut self, path: impl Into<String>) {
        self.source = Some(Source::File(path.into()));
    }

    /// Attach an HTTP/S3 URL as the data source for lazy reads.
    #[cfg(feature = "http")]
    pub fn set_url(&mut self, url: impl Into<String>) {
        self.source = Some(Source::Url(url.into()));
    }

    /// Read a channel by name as a [`Signal`] using the attached [`Source`].
    ///
    /// Values are paired with the channel's group master (time) axis. This is
    /// the lazy read path: the byte-range request happens now, not at index
    /// build time. Errors if no source is attached (see [`MdfIndex::set_file`] /
    /// [`MdfIndex::set_url`]).
    pub fn read(&self, name: &str) -> Result<Signal, MdfError> {
        let (g, c) = self.locate(name).ok_or_else(|| {
            MdfError::BlockSerializationError(format!("Channel '{}' not found", name))
        })?;
        self.read_signal(g, c)
    }

    /// [`MdfIndex::read`] addressed by group name + channel name.
    pub fn read_in(&self, group: &str, name: &str) -> Result<Signal, MdfError> {
        let (g, c) = self.locate_in(group, name).ok_or_else(|| {
            MdfError::BlockSerializationError(format!(
                "Channel '{}' not found in group '{}'",
                name, group
            ))
        })?;
        self.read_signal(g, c)
    }

    /// Decode a channel + its group master from the attached source.
    fn read_signal(&self, g: usize, c: usize) -> Result<Signal, MdfError> {
        let (name, unit, master) = {
            let channel = &self.channel_groups[g].channels[c];
            let master = self.channel_groups[g]
                .channels
                .iter()
                .position(|ch| ch.is_master())
                .filter(|&m| m != c);
            (channel.name.clone().unwrap_or_default(), channel.unit.clone(), master)
        };

        let values = self.read_values_via_source(g, c)?;
        let timestamps = match master {
            Some(m) => self.read_values_f64_via_source(g, m)?,
            None => Vec::new(),
        };

        Ok(Signal { name, unit, timestamps, values })
    }

    /// Resolve the attached [`Source`], erroring with a helpful message if none.
    fn require_source(&self) -> Result<&Source, MdfError> {
        self.source.as_ref().ok_or_else(|| {
            MdfError::BlockSerializationError(
                "no data source attached to index; build with from_file/from_url or call set_file/set_url".to_string(),
            )
        })
    }

    /// 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> {
        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 = CachingRangeReader::new(http);
                cached.set_bypass(true);
                self.read_channel_values(g, c, &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> {
        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 = CachingRangeReader::new(http);
                cached.set_bypass(true);
                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 + 7) / 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.
    pub fn byte_ranges(&self, name: &str) -> Result<Vec<(u64, u64)>, MdfError> {
        let (g, c) = self.locate(name).ok_or_else(|| {
            MdfError::BlockSerializationError(format!("Channel '{}' not found", name))
        })?;
        self.get_channel_byte_ranges(g, c)
    }

    /// Byte ranges for a channel addressed by group name + channel name.
    pub fn byte_ranges_in(&self, group: &str, name: &str) -> Result<Vec<(u64, u64)>, MdfError> {
        let (g, c) = self.locate_in(group, name).ok_or_else(|| {
            MdfError::BlockSerializationError(format!(
                "Channel '{}' not found in group '{}'",
                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,
    ) -> Result<Vec<(u64, u64)>, MdfError> {
        let (g, c) = self.locate(name).ok_or_else(|| {
            MdfError::BlockSerializationError(format!("Channel '{}' not found", name))
        })?;
        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()))?;

        // VLSD channels are not supported: decoding their inline SD offsets
        // as payload would return garbage.
        Self::ensure_not_vlsd(channel)?;

        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(channel);
        let has_conversion = channel.conversion.is_some();

        for data_block in &group.data_blocks {
            let block_data = reader
                .read_range(data_block.file_offset + 24, Self::data_section_size(data_block)?)?;
            Self::decode_records_to_f64(&block_data, record_size, group, channel, &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()))?;

        // VLSD channels are not supported: decoding their inline SD offsets
        // as payload would return garbage.
        Self::ensure_not_vlsd(channel)?;

        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, channel, &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()))?;

        // VLSD channels are not supported: decoding their inline SD offsets
        // as payload would return garbage.
        Self::ensure_not_vlsd(channel)?;

        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(channel);
        let has_conversion = channel.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, &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> {
        let data_len = Self::data_section_size(data_block)?;
        let bounds = data_block
            .file_offset
            .checked_add(24)
            .and_then(|start| start.checked_add(data_len).map(|end| (start, end)))
            .and_then(|(start, end)| {
                Some((usize::try_from(start).ok()?, usize::try_from(end).ok()?))
            });
        let (data_start, data_end) = match bounds {
            Some(b) => b,
            None => {
                return Err(MdfError::TooShortBuffer {
                    actual: file_data.len(),
                    expected: usize::MAX,
                    file: file!(),
                    line: line!(),
                });
            }
        };
        if data_end > file_data.len() {
            return Err(MdfError::TooShortBuffer {
                actual: file_data.len(),
                expected: data_end,
                file: file!(),
                line: line!(),
            });
        }
        Ok(&file_data[data_start..data_end])
    }
}

/// 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
    }

    fn locate(&self, name: &str) -> Result<(usize, usize), MdfError> {
        self.index.locate(name).ok_or_else(|| {
            MdfError::BlockSerializationError(format!("Channel '{}' not found", name))
        })
    }

    fn locate_in(&self, group: &str, name: &str) -> Result<(usize, usize), MdfError> {
        self.index.locate_in(group, name).ok_or_else(|| {
            MdfError::BlockSerializationError(format!(
                "Channel '{}' not found in group '{}'",
                name, group
            ))
        })
    }

    /// Read all samples of a channel by name (first match across groups).
    ///
    /// Conversions stored in the index are applied; invalid samples are `None`.
    pub fn values(&mut self, name: &str) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        let (g, c) = self.locate(name)?;
        self.index.read_channel_values(g, c, &mut self.reader)
    }

    /// Read all samples of a channel, addressed by group name + channel name.
    pub fn values_in(
        &mut self,
        group: &str,
        name: &str,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        let (g, c) = self.locate_in(group, name)?;
        self.index.read_channel_values(g, c, &mut self.reader)
    }

    /// Fast path: read a numeric channel by name as `Vec<f64>`.
    ///
    /// Invalid / non-numeric samples are `f64::NAN`. Conversions that reduce to
    /// a linear scale are applied inline.
    pub fn values_f64(&mut self, name: &str) -> Result<Vec<f64>, MdfError> {
        let (g, c) = self.locate(name)?;
        self.index.read_channel_values_as_f64(g, c, &mut self.reader)
    }

    /// Fast `f64` path addressed by group name + channel name.
    pub fn values_f64_in(&mut self, group: &str, name: &str) -> Result<Vec<f64>, MdfError> {
        let (g, c) = self.locate_in(group, name)?;
        self.index.read_channel_values_as_f64(g, c, &mut self.reader)
    }

    /// Read a channel by name as a [`Signal`] (values paired with the group's
    /// master/time axis), using this reader's bound source.
    pub fn signal(&mut self, name: &str) -> Result<Signal, MdfError> {
        let (g, c) = self.locate(name)?;
        self.read_signal(g, c)
    }

    /// [`MdfReader::signal`] addressed by group name + channel name.
    pub fn signal_in(&mut self, group: &str, name: &str) -> Result<Signal, MdfError> {
        let (g, c) = self.locate_in(group, name)?;
        self.read_signal(g, c)
    }

    fn read_signal(&mut self, g: usize, c: usize) -> Result<Signal, MdfError> {
        let (name, unit, master) = {
            let group = &self.index.channel_groups[g];
            let channel = &group.channels[c];
            let master = group
                .channels
                .iter()
                .position(|ch| ch.is_master())
                .filter(|&m| m != c);
            (channel.name.clone().unwrap_or_default(), channel.unit.clone(), master)
        };

        let values = self.index.read_channel_values(g, c, &mut self.reader)?;
        let timestamps = match master {
            Some(m) => self
                .index
                .read_channel_values(g, m, &mut self.reader)?
                .iter()
                .map(decoded_opt_to_f64)
                .collect(),
            None => Vec::new(),
        };
        Ok(Signal { name, unit, timestamps, values })
    }
}