Skip to main content

mf4_rs/
index.rs

1//! MDF File Indexing System
2//!
3//! This module provides functionality to create lightweight indexes of MDF files
4//! that can be serialized to JSON and used later to read specific channel data
5//! without parsing the entire file structure.
6
7use serde::{Deserialize, Serialize};
8use crate::api::mdf::Mdf;
9use crate::blocks::common::{DataType, BlockHeader, BlockParse};
10use crate::blocks::conversion::{ConversionBlock, ConversionType};
11use crate::error::MdfError;
12#[cfg(feature = "http")]
13use crate::fragments::{merge_ranges_bridging, FragmentStore, RecordingRangeReader};
14use crate::parsing::decoder::{check_value_validity, decode_channel_value, decode_channel_value_with_validity, decode_f64_from_record, vlsd_offset, DecodedValue};
15use crate::parsing::record_stream::RecordCarry;
16use crate::signal::Signal;
17use crate::types::{
18    logical_group_members, merge_group_infos, resolve_records, search_time_window, ChannelInfo, ConversionInfo,
19    GroupInfo, ReadOptions, TimeRange, Window,
20};
21use std::borrow::Cow;
22use std::collections::HashMap;
23
24/// Largest single read issued when coalescing adjacent data blocks (64 MiB).
25const MAX_COALESCED_READ: u64 = 64 * 1024 * 1024;
26
27/// Represents the location and metadata of data blocks in the file
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct DataBlockInfo {
30    /// File offset where the data block starts
31    pub file_offset: u64,
32    /// Size of the data block in bytes
33    pub size: u64,
34    /// Whether this is a compressed block (DZ)
35    pub is_compressed: bool,
36}
37
38/// Channel metadata needed for decoding values
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct IndexedChannel {
41    /// Channel name
42    pub name: Option<String>,
43    /// Physical unit
44    pub unit: Option<String>,
45    /// Channel comment (`##TX` text, or the raw `##MD` XML)
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub comment: Option<String>,
48    /// Data type of the channel
49    pub data_type: DataType,
50    /// Byte offset within each record
51    pub byte_offset: u32,
52    /// Bit offset within the byte
53    pub bit_offset: u8,
54    /// Number of bits for this channel
55    pub bit_count: u32,
56    /// Channel type (0=data, 1=VLSD, 2=master, etc.)
57    pub channel_type: u8,
58    /// Channel flags (includes invalidation bit flags)
59    pub flags: u32,
60    /// Position of invalidation bit within invalidation bytes
61    pub pos_invalidation_bit: u32,
62    /// Conversion block for unit conversion (if any).
63    ///
64    /// May be `None` even when the channel *has* a conversion: index builds
65    /// that read a file over the network ([`MdfIndex::from_url`] /
66    /// [`MdfIndex::from_range_reader`]) do **not** fetch and resolve the
67    /// conversion block up front — they only record its file offset in
68    /// [`conversion_addr`](Self::conversion_addr) and resolve it lazily on the
69    /// first value read. Indexes built from a local file or an in-memory buffer
70    /// still resolve eagerly, so this stays populated for them. Read paths
71    /// prefer a resolved conversion here and otherwise fall back to
72    /// `conversion_addr`.
73    pub conversion: Option<ConversionBlock>,
74    /// File offset of the channel's `##CC` conversion block (0 = none).
75    ///
76    /// Recorded so the conversion can be resolved lazily at read time when it
77    /// was not resolved during index building (the remote / range-reader
78    /// path). Defaults to 0 for older serialized indexes, which carry the fully
79    /// resolved [`conversion`](Self::conversion) instead.
80    #[serde(default)]
81    pub conversion_addr: u64,
82    /// For VLSD channels: address of signal data blocks
83    pub vlsd_data_address: Option<u64>,
84    /// For VLSD channels: locations of the ##SD fragments in chain order.
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub vlsd_data_blocks: Vec<DataBlockInfo>,
87}
88
89impl IndexedChannel {
90    /// `true` if this is the group's master channel (usually time): a
91    /// regular (`cn_type` 2) or virtual (`cn_type` 3) master.
92    pub fn is_master(&self) -> bool {
93        self.channel_type == 2 || self.channel_type == 3
94    }
95
96    /// `true` for a virtual channel (`cn_type` 3 master or 6 data): it stores
97    /// no bytes, its raw value is the record index.
98    pub fn is_virtual(&self) -> bool {
99        self.channel_type == 3 || self.channel_type == 6
100    }
101
102    /// This channel's metadata as a plain [`ChannelInfo`].
103    pub fn info(&self) -> ChannelInfo {
104        ChannelInfo {
105            name: self.name.clone(),
106            unit: self.unit.clone(),
107            comment: self.comment.clone(),
108            data_type: self.data_type.name().to_string(),
109            bit_count: self.bit_count,
110            is_master: self.is_master(),
111            is_vlsd: self.is_vlsd(),
112            has_conversion: self.conversion.is_some() || self.conversion_addr != 0,
113        }
114    }
115
116    /// `true` if this is a variable-length (VLSD) channel.
117    pub fn is_vlsd(&self) -> bool {
118        self.channel_type == 1 && self.vlsd_data_address.is_some()
119    }
120
121    /// Create a lightweight `ChannelBlock` for the decoder functions (which
122    /// only read the record layout): the name and conversion are not cloned.
123    /// Build it once per read and reuse it across all records.
124    fn to_decode_only_channel_block(&self) -> crate::blocks::channel_block::ChannelBlock {
125        Self::build_channel_block(
126            self.channel_type,
127            self.data_type.clone(),
128            self.bit_offset,
129            self.byte_offset,
130            self.bit_count,
131            self.flags,
132            self.pos_invalidation_bit,
133            None,
134            None,
135        )
136    }
137
138    fn build_channel_block(
139        channel_type: u8,
140        data_type: DataType,
141        bit_offset: u8,
142        byte_offset: u32,
143        bit_count: u32,
144        flags: u32,
145        pos_invalidation_bit: u32,
146        name: Option<String>,
147        conversion: Option<ConversionBlock>,
148    ) -> crate::blocks::channel_block::ChannelBlock {
149        crate::blocks::channel_block::ChannelBlock {
150            header: crate::blocks::common::BlockHeader {
151                id: "##CN".to_string(),
152                reserved0: 0,
153                block_len: 160,
154                links_nr: 8,
155            },
156            next_ch_addr: 0,
157            component_addr: 0,
158            name_addr: 0,
159            source_addr: 0,
160            conversion_addr: 0,
161            data: 0,
162            unit_addr: 0,
163            comment_addr: 0,
164            channel_type,
165            sync_type: 0,
166            data_type,
167            bit_offset,
168            byte_offset,
169            bit_count,
170            flags,
171            pos_invalidation_bit,
172            precision: 0,
173            reserved1: 0,
174            attachment_nr: 0,
175            min_raw_value: 0.0,
176            max_raw_value: 0.0,
177            lower_limit: 0.0,
178            upper_limit: 0.0,
179            lower_ext_limit: 0.0,
180            upper_ext_limit: 0.0,
181            name,
182            conversion,
183        }
184    }
185}
186
187/// Channel group metadata and layout information
188#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct IndexedChannelGroup {
190    /// Group name
191    pub name: Option<String>,
192    /// Comment
193    pub comment: Option<String>,
194    /// Size of record ID in bytes
195    pub record_id_len: u8,
196    /// Total size of each record in bytes (excluding record ID and invalidation bytes)
197    pub record_size: u32,
198    /// Number of invalidation bytes per record
199    pub invalidation_bytes: u32,
200    /// Number of records in this group
201    pub record_count: u64,
202    /// Channels in this group
203    pub channels: Vec<IndexedChannel>,
204    /// Data block locations for this channel group
205    pub data_blocks: Vec<DataBlockInfo>,
206    /// Index (into [`MdfIndex::channel_groups`]) of the group holding this
207    /// group's master channel when it is stored *remotely* — the MDF 4.2
208    /// column-oriented layout, where each signal has its own channel group and
209    /// points at a shared time group via `cg_cg_master`. `None` when the master
210    /// is local (or there is none).
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub master_group: Option<usize>,
213}
214
215impl IndexedChannelGroup {
216    /// Find a channel in this group by name (first match).
217    pub fn channel(&self, name: &str) -> Option<&IndexedChannel> {
218        self.channels
219            .iter()
220            .find(|c| c.name.as_deref() == Some(name))
221    }
222
223    /// Names of every named channel in this group, in record order.
224    pub fn channel_names(&self) -> Vec<&str> {
225        self.channels
226            .iter()
227            .filter_map(|c| c.name.as_deref())
228            .collect()
229    }
230
231    /// The group's master channel (channel type 2), if any.
232    pub fn master_channel(&self) -> Option<&IndexedChannel> {
233        self.channels.iter().find(|c| c.is_master())
234    }
235}
236
237/// Where an [`MdfIndex`] reads sample data from when asked to.
238///
239/// The source is *not* serialized with the index — after [`MdfIndex::load`]
240/// re-attach one with [`MdfIndex::set_source`]. Building an
241/// index never reads sample data; the actual byte-range reads happen lazily on
242/// [`MdfIndex::read`].
243#[derive(Debug, Clone)]
244pub enum Source {
245    /// A local file path, read via memory map.
246    File(String),
247    /// An HTTP/S3 URL, read via range requests.
248    #[cfg(feature = "http")]
249    Url(String),
250}
251
252impl Source {
253    /// The file path or URL as a string.
254    pub fn as_str(&self) -> &str {
255        match self {
256            Source::File(p) => p,
257            #[cfg(feature = "http")]
258            Source::Url(u) => u,
259        }
260    }
261}
262
263/// A string is a [`Source`]: `http://` / `https://` URLs become
264/// [`Source::Url`] (with the `http` feature), anything else a file path.
265/// The URL scheme of `value` (`"https"` for `https://…`), if it has one.
266/// A Windows drive path (`C:\\…`, `C:/…`) has none.
267fn url_scheme(value: &str) -> Option<&str> {
268    let (scheme, _) = value.split_once("://")?;
269    let mut chars = scheme.chars();
270    let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
271        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
272    (valid && scheme.len() > 1).then_some(scheme)
273}
274
275/// True for an `http://` / `https://` URL (scheme matched case-insensitively).
276fn is_http_url(value: &str) -> bool {
277    url_scheme(value).is_some_and(|s| s.eq_ignore_ascii_case("http") || s.eq_ignore_ascii_case("https"))
278}
279
280impl From<&str> for Source {
281    fn from(value: &str) -> Self {
282        #[cfg(feature = "http")]
283        if is_http_url(value) {
284            return Source::Url(value.to_string());
285        }
286        Source::File(value.to_string())
287    }
288}
289
290impl From<String> for Source {
291    fn from(value: String) -> Self {
292        Source::from(value.as_str())
293    }
294}
295
296/// Ranges recorded in one batched round that lie at most this far apart are
297/// fetched as one request (mirrors `WINDOW_BRIDGE_BYTES` in the TS driver).
298#[cfg(feature = "http")]
299const BATCH_BRIDGE_BYTES: u64 = 4 * 1024;
300
301/// Upper bound on the rounds of [`MdfIndex::batched_reads`].
302#[cfg(feature = "http")]
303const MAX_BATCH_ROUNDS: usize = 1_000;
304
305/// Batched reads fetch a range larger than this as several concurrent
306/// requests of at most this size (8 MiB): one connection to an object store
307/// is far slower than several in parallel.
308#[cfg(feature = "http")]
309const PARALLEL_CHUNK_BYTES: u64 = 8 * 1024 * 1024;
310
311/// Whole-channel URL reads fetch the batch at once (concurrently) only while
312/// it needs at most this many bytes (256 MiB); larger reads stream one data
313/// section at a time.
314#[cfg(feature = "http")]
315const BATCH_MEMORY_LIMIT: u64 = 256 * 1024 * 1024;
316
317/// URL reader for streamed whole-channel reads: serves bytes already fetched
318/// (deferred conversion blocks) from `store`, and fetches a range larger than
319/// [`PARALLEL_CHUNK_BYTES`] as concurrent chunks.
320#[cfg(feature = "http")]
321struct ChunkedUrlReader {
322    http: HttpRangeReader,
323    store: FragmentStore,
324}
325
326#[cfg(feature = "http")]
327impl ByteRangeReader for ChunkedUrlReader {
328    type Error = MdfError;
329
330    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
331        if let crate::fragments::Coverage::Full(bytes) = self.store.assemble(offset, length)? {
332            return Ok(bytes);
333        }
334        if length <= PARALLEL_CHUNK_BYTES {
335            return self.http.read_range(offset, length);
336        }
337        let parts = self.http.read_ranges_parallel(&split_spans(vec![(offset, length)], PARALLEL_CHUNK_BYTES))?;
338        let mut out = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
339        for part in parts {
340            out.extend_from_slice(&part);
341        }
342        Ok(out)
343    }
344}
345
346/// Split every `(offset, length)` span longer than `chunk` into consecutive
347/// pieces of at most `chunk` bytes.
348#[cfg(feature = "http")]
349fn split_spans(spans: Vec<(u64, u64)>, chunk: u64) -> Vec<(u64, u64)> {
350    let mut out = Vec::with_capacity(spans.len());
351    for (offset, length) in spans {
352        let mut at = 0;
353        while at < length {
354            let take = chunk.min(length - at);
355            out.push((offset + at, take));
356            at += take;
357        }
358    }
359    out
360}
361
362/// Reader over an index's attached [`Source`], for windowed reads.
363enum SourceReader {
364    #[cfg(not(target_arch = "wasm32"))]
365    File(MmapRangeReader),
366    #[cfg(feature = "http")]
367    Url(CachingRangeReader<HttpRangeReader>),
368}
369
370impl ByteRangeReader for SourceReader {
371    type Error = MdfError;
372
373    #[allow(unused_variables)]
374    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
375        match *self {
376            #[cfg(not(target_arch = "wasm32"))]
377            SourceReader::File(ref mut r) => r.read_range(offset, length),
378            #[cfg(feature = "http")]
379            SourceReader::Url(ref mut r) => r.read_range(offset, length),
380        }
381    }
382}
383
384/// Record windows resolved during one `read_many`, keyed by the time axis
385/// searched (`None` for a record window) and the group's record count.
386type WindowCache = HashMap<(Option<(usize, usize)>, u64), (u64, u64)>;
387
388/// Time axes decoded during one `read_many`, keyed by the master's
389/// `(group, channel)` and the record window `(start, count)`.
390type AxisCache = HashMap<(usize, usize, u64, u64), Vec<f64>>;
391
392/// Complete MDF file index
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct MdfIndex {
395    /// File size for validation
396    pub file_size: u64,
397    /// Start time of the measurement in nanoseconds since epoch (from MDF header)
398    /// None if the start time is not set (0) in the file
399    pub start_time_ns: Option<u64>,
400    /// Channel groups in the file
401    pub channel_groups: Vec<IndexedChannelGroup>,
402    /// The data source for lazy value reads. Populated by `from_file` /
403    /// `from_url`, re-attachable after load via `set_source`. Never
404    /// serialized — an index file is portable; the source is environment-local.
405    #[serde(skip)]
406    pub source: Option<Source>,
407}
408
409/// Trait for reading byte ranges from different sources (files, HTTP, etc.)
410pub trait ByteRangeReader {
411    type Error;
412
413    /// Read bytes from the specified range
414    /// Returns the requested bytes or an error
415    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error>;
416
417    /// Read an *optional* metadata range that the walk can proceed without.
418    ///
419    /// Behaves exactly like [`read_range`](Self::read_range) by default, so
420    /// on-demand readers (file, HTTP) are unaffected. Incremental readers that
421    /// *gather* the ranges they still need — rather than fetching one at a time
422    /// — override this to record a gap and return `Ok(None)` instead of
423    /// aborting. That lets a single metadata walk collect **every** still-missing
424    /// leaf range (channel names, units, group comments) at once, turning an
425    /// O(N²) fetch-restart loop into a handful of passes. Returning `None` means
426    /// "these bytes are not available yet"; the caller treats the value as
427    /// absent for this pass. Structural reads (block headers whose bytes yield
428    /// the next link address) must keep using [`read_range`](Self::read_range) —
429    /// the walk cannot continue past those without the real bytes.
430    fn read_range_optional(
431        &mut self,
432        offset: u64,
433        length: u64,
434    ) -> Result<Option<Vec<u8>>, Self::Error> {
435        self.read_range(offset, length).map(Some)
436    }
437
438    /// True when this reader is a gap-discovery probe: it cannot serve every
439    /// range and records the misses instead of returning data. Metadata walks
440    /// may then skip an unreadable subtree and keep discovering gaps elsewhere
441    /// rather than aborting on the first miss.
442    ///
443    /// A walk driven by a probing reader produces a **partial** result: callers
444    /// MUST discard it and retry once the recorded ranges have been supplied.
445    fn is_probing(&self) -> bool {
446        false
447    }
448}
449
450/// Local file reader implementation.
451///
452/// Not available on `wasm32-unknown-unknown`; implement [`ByteRangeReader`] over
453/// a `Cursor<Vec<u8>>` or a JS `Blob`-backed reader instead.
454#[cfg(not(target_arch = "wasm32"))]
455pub struct FileRangeReader {
456    file: std::fs::File,
457}
458
459#[cfg(not(target_arch = "wasm32"))]
460impl FileRangeReader {
461    pub fn new(file_path: &str) -> Result<Self, MdfError> {
462        let file = std::fs::File::open(file_path)
463            .map_err(MdfError::IOError)?;
464        Ok(Self { file })
465    }
466}
467
468#[cfg(not(target_arch = "wasm32"))]
469impl ByteRangeReader for FileRangeReader {
470    type Error = MdfError;
471
472    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
473        use std::io::{Read, Seek, SeekFrom};
474
475        // Validate against the real file length *before* allocating: a forged
476        // or stale index could otherwise request an absurd length and abort
477        // the process on allocation failure.
478        let file_len = self.file.metadata().map_err(MdfError::IOError)?.len();
479        match offset.checked_add(length) {
480            Some(end) if end <= file_len => {}
481            _ => {
482                return Err(MdfError::TooShortBuffer {
483                    actual: file_len as usize,
484                    expected: offset.saturating_add(length) as usize,
485                    file: file!(),
486                    line: line!(),
487                });
488            }
489        }
490
491        self.file.seek(SeekFrom::Start(offset))
492            .map_err(MdfError::IOError)?;
493
494        let mut buffer = vec![0u8; length as usize];
495        self.file.read_exact(&mut buffer)
496            .map_err(MdfError::IOError)?;
497
498        Ok(buffer)
499    }
500}
501
502/// Memory-mapped file reader implementation.
503///
504/// Not available on `wasm32-unknown-unknown`.
505#[cfg(not(target_arch = "wasm32"))]
506pub struct MmapRangeReader {
507    mmap: memmap2::Mmap,
508}
509
510#[cfg(not(target_arch = "wasm32"))]
511impl MmapRangeReader {
512    pub fn new(file_path: &str) -> Result<Self, MdfError> {
513        let file = std::fs::File::open(file_path).map_err(MdfError::IOError)?;
514        let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
515        Ok(Self { mmap })
516    }
517}
518
519#[cfg(not(target_arch = "wasm32"))]
520impl ByteRangeReader for MmapRangeReader {
521    type Error = MdfError;
522
523    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
524        // Checked arithmetic: a forged offset/length must error, not wrap.
525        let end = match offset
526            .checked_add(length)
527            .and_then(|e| usize::try_from(e).ok())
528        {
529            Some(end) if end <= self.mmap.len() => end,
530            _ => {
531                return Err(MdfError::TooShortBuffer {
532                    actual: self.mmap.len(),
533                    expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
534                    file: file!(),
535                    line: line!(),
536                });
537            }
538        };
539        Ok(self.mmap[offset as usize..end].to_vec())
540    }
541}
542
543/// In-memory byte-slice reader — available on all targets including WASM.
544///
545/// Wraps an owned `Vec<u8>` and satisfies [`ByteRangeReader`] by slicing
546/// directly into it.  Useful when the entire file has already been loaded
547/// into memory (e.g. via `Blob.arrayBuffer()` in a browser Worker).
548pub struct SliceRangeReader {
549    data: Vec<u8>,
550}
551
552impl SliceRangeReader {
553    pub fn new(data: Vec<u8>) -> Self {
554        Self { data }
555    }
556}
557
558impl ByteRangeReader for SliceRangeReader {
559    type Error = MdfError;
560
561    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
562        // Checked arithmetic: a forged offset/length must error, not wrap.
563        let end = match offset
564            .checked_add(length)
565            .and_then(|e| usize::try_from(e).ok())
566        {
567            Some(end) if end <= self.data.len() => end,
568            _ => {
569                return Err(MdfError::TooShortBuffer {
570                    actual: self.data.len(),
571                    expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
572                    file: file!(),
573                    line: line!(),
574                });
575            }
576        };
577        Ok(self.data[offset as usize..end].to_vec())
578    }
579}
580
581/// Borrowing counterpart to [`SliceRangeReader`] — a [`ByteRangeReader`] over a
582/// borrowed `&[u8]` (e.g. a memory map), so the mmap-based index paths can
583/// reuse the generic reader logic without cloning the whole file into a `Vec`.
584struct BorrowedSliceReader<'a> {
585    data: &'a [u8],
586}
587
588impl<'a> ByteRangeReader for BorrowedSliceReader<'a> {
589    type Error = MdfError;
590
591    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
592        // Checked arithmetic: a forged offset/length must error, not wrap.
593        let end = match offset
594            .checked_add(length)
595            .and_then(|e| usize::try_from(e).ok())
596        {
597            Some(end) if end <= self.data.len() => end,
598            _ => {
599                return Err(MdfError::TooShortBuffer {
600                    actual: self.data.len(),
601                    expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
602                    file: file!(),
603                    line: line!(),
604                });
605            }
606        };
607        Ok(self.data[offset as usize..end].to_vec())
608    }
609}
610
611/// Caching wrapper around any [`ByteRangeReader`].
612///
613/// During the metadata phase of building an [`MdfIndex`], the parser issues
614/// many small reads (block headers, channel metadata, text blocks). Without
615/// caching, each becomes a round-trip on a remote backend. `CachingRangeReader`
616/// fetches in larger aligned chunks (default 1 MiB) and serves overlapping
617/// reads from memory, collapsing hundreds of small reads into a handful of
618/// underlying requests.
619///
620/// For value reads — which span large slices of data blocks — call
621/// [`CachingRangeReader::set_bypass`] to forward each read directly to the
622/// underlying reader without populating the cache.
623pub struct CachingRangeReader<R: ByteRangeReader<Error = MdfError>> {
624    inner: R,
625    chunks: std::collections::BTreeMap<u64, Vec<u8>>,
626    chunk_size: u64,
627    bypass: bool,
628    underlying_requests: u64,
629    cache_hits: u64,
630    /// Total size of the underlying resource, once learned. Whole-chunk
631    /// fetches are clamped against it so strict inner readers (which error on
632    /// reads past EOF) still work when the resource size is not a multiple of
633    /// `chunk_size`.
634    known_size: Option<u64>,
635}
636
637impl<R: ByteRangeReader<Error = MdfError>> CachingRangeReader<R> {
638    /// The wrapped reader.
639    #[allow(dead_code)]
640    pub(crate) fn inner_mut(&mut self) -> &mut R {
641        &mut self.inner
642    }
643
644    /// The wrapped reader and every cached chunk as `(offset, bytes)`.
645    #[allow(dead_code)]
646    pub(crate) fn into_parts(self) -> (R, Vec<(u64, Vec<u8>)>) {
647        let chunk_size = self.chunk_size;
648        let chunks = self
649            .chunks
650            .into_iter()
651            .filter(|(_, bytes)| !bytes.is_empty())
652            .map(|(i, bytes)| (i * chunk_size, bytes))
653            .collect();
654        (self.inner, chunks)
655    }
656
657    /// Wrap a reader with the default chunk size (1 MiB).
658    pub fn new(inner: R) -> Self {
659        Self::with_chunk_size(inner, 1 << 20)
660    }
661
662    /// Wrap a reader with a custom chunk size in bytes.
663    pub fn with_chunk_size(inner: R, chunk_size: u64) -> Self {
664        assert!(chunk_size > 0, "chunk_size must be > 0");
665        Self {
666            inner,
667            chunks: std::collections::BTreeMap::new(),
668            chunk_size,
669            bypass: false,
670            underlying_requests: 0,
671            cache_hits: 0,
672            known_size: None,
673        }
674    }
675
676    /// Tell the cache the total size of the underlying resource (e.g. from an
677    /// HTTP size probe), so the final chunk is requested at its true length
678    /// instead of failing short and being re-requested.
679    pub fn set_known_size(&mut self, size: u64) {
680        self.known_size = Some(size);
681    }
682
683    /// When set, reads are served from already-cached chunks when fully
684    /// covered, and otherwise forward directly to the underlying reader without
685    /// populating the cache. Use during value-read phases so large data-block
686    /// fetches do not pollute the cache, while small metadata reads that were
687    /// already pulled in during the index walk (such as a conversion block
688    /// resolved lazily on first read) remain free.
689    pub fn set_bypass(&mut self, bypass: bool) {
690        self.bypass = bypass;
691    }
692
693    /// Number of read calls forwarded to the underlying reader.
694    pub fn underlying_requests(&self) -> u64 {
695        self.underlying_requests
696    }
697
698    /// Number of read calls fully satisfied from cache.
699    pub fn cache_hits(&self) -> u64 {
700        self.cache_hits
701    }
702
703    /// Pre-fetch a contiguous range into the cache.
704    pub fn prefetch(&mut self, offset: u64, length: u64) -> Result<(), MdfError> {
705        if length == 0 {
706            return Ok(());
707        }
708        self.read_range(offset, length).map(|_| ())
709    }
710
711    /// Try to satisfy a read entirely from chunks already in the cache,
712    /// without issuing any underlying request. Returns `None` if any covering
713    /// chunk is absent or too short (e.g. an EOF-clamped tail), leaving the
714    /// caller to fetch. Used in bypass mode so small reads that land in
715    /// already-fetched metadata chunks (e.g. a lazily-resolved conversion
716    /// block) stay free, while large uncached data reads still forward straight
717    /// through.
718    fn try_serve_from_cache(&self, offset: u64, length: u64) -> Option<Vec<u8>> {
719        let first = offset / self.chunk_size;
720        let last = (offset + length - 1) / self.chunk_size;
721        let read_end = offset + length;
722        for i in first..=last {
723            let chunk = self.chunks.get(&i)?;
724            let chunk_start = i * self.chunk_size;
725            let cached_end = chunk_start + chunk.len() as u64;
726            let needed_end = read_end.min(chunk_start + self.chunk_size);
727            if cached_end < needed_end {
728                return None;
729            }
730        }
731        let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
732        let mut remaining = length as usize;
733        let mut cursor = offset;
734        while remaining > 0 {
735            let chunk_index = cursor / self.chunk_size;
736            let chunk_offset = (cursor % self.chunk_size) as usize;
737            let chunk = self.chunks.get(&chunk_index)?;
738            if chunk_offset >= chunk.len() {
739                return None;
740            }
741            let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
742            out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
743            cursor += take as u64;
744            remaining -= take;
745            if take == 0 {
746                return None;
747            }
748        }
749        Some(out)
750    }
751
752    fn ensure_chunks(&mut self, first: u64, last: u64, requested_end: u64) -> Result<(), MdfError> {
753        // Walk [first..=last], find each contiguous run of missing chunks,
754        // issue one read per run.
755        let mut idx = first;
756        while idx <= last {
757            if self.chunks.contains_key(&idx) {
758                idx += 1;
759                continue;
760            }
761            let run_start = idx;
762            while idx <= last && !self.chunks.contains_key(&idx) {
763                idx += 1;
764            }
765            let run_end = idx - 1;
766            let read_offset = run_start * self.chunk_size;
767            let mut read_len = (run_end - run_start + 1) * self.chunk_size;
768
769            // Clamp against the known end of the resource: strict inner
770            // readers reject reads past EOF, and the final chunk is allowed
771            // to be short.
772            if let Some(size) = self.known_size {
773                if read_offset >= size {
774                    for slot in run_start..=run_end {
775                        self.chunks.insert(slot, Vec::new());
776                    }
777                    continue;
778                }
779                read_len = read_len.min(size - read_offset);
780            }
781
782            let bytes = match self.inner.read_range(read_offset, read_len) {
783                Ok(b) => {
784                    self.underlying_requests += 1;
785                    b
786                }
787                Err(e) => {
788                    self.underlying_requests += 1;
789                    // The whole-chunk read may extend past EOF (the resource
790                    // size need not be a multiple of chunk_size). Learn the
791                    // true end from the error when it reports one, otherwise
792                    // fall back to the span the caller actually asked for,
793                    // and retry clamped.
794                    let clamp_to = match &e {
795                        MdfError::TooShortBuffer { actual, .. }
796                            if (*actual as u64) > read_offset
797                                && (*actual as u64) < read_offset + read_len =>
798                        {
799                            self.known_size = Some(*actual as u64);
800                            *actual as u64
801                        }
802                        _ if requested_end > read_offset
803                            && requested_end < read_offset + read_len =>
804                        {
805                            requested_end
806                        }
807                        _ => return Err(e),
808                    };
809                    let b = self.inner.read_range(read_offset, clamp_to - read_offset)?;
810                    self.underlying_requests += 1;
811                    b
812                }
813            };
814
815            // Split the response into chunk-sized pieces. The last chunk
816            // may be short if the file ends partway through it.
817            for (i, slot) in (run_start..=run_end).enumerate() {
818                let start = i * self.chunk_size as usize;
819                if start >= bytes.len() {
820                    self.chunks.insert(slot, Vec::new());
821                    continue;
822                }
823                let end = std::cmp::min(start + self.chunk_size as usize, bytes.len());
824                self.chunks.insert(slot, bytes[start..end].to_vec());
825            }
826        }
827        Ok(())
828    }
829}
830
831impl<R: ByteRangeReader<Error = MdfError>> ByteRangeReader for CachingRangeReader<R> {
832    type Error = MdfError;
833
834    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
835        if length == 0 {
836            return Ok(Vec::new());
837        }
838        if self.bypass {
839            // Serve from already-cached chunks when possible (e.g. a small
840            // conversion block lazily resolved at read time that lands in a
841            // metadata chunk fetched during the index walk); otherwise forward
842            // the (typically large data-block) read straight through.
843            if let Some(bytes) = self.try_serve_from_cache(offset, length) {
844                self.cache_hits += 1;
845                return Ok(bytes);
846            }
847            let bytes = self.inner.read_range(offset, length)?;
848            self.underlying_requests += 1;
849            return Ok(bytes);
850        }
851
852        let first = offset / self.chunk_size;
853        let last = (offset + length - 1) / self.chunk_size;
854        let read_end = offset + length;
855
856        // A chunk cached from an earlier EOF-clamped read may be shorter than
857        // the span this read needs from it. Drop such chunks so ensure_chunks
858        // refetches them (clamped to this read's span or the known size).
859        for i in first..=last {
860            if let Some(chunk) = self.chunks.get(&i) {
861                let chunk_start = i * self.chunk_size;
862                let cached_end = chunk_start + chunk.len() as u64;
863                let mut needed_end = read_end.min(chunk_start + self.chunk_size);
864                if let Some(size) = self.known_size {
865                    needed_end = needed_end.min(size);
866                }
867                if cached_end < needed_end {
868                    self.chunks.remove(&i);
869                }
870            }
871        }
872
873        // Track cache-hit metric only when no underlying read is required.
874        let need_fetch = (first..=last).any(|i| !self.chunks.contains_key(&i));
875        self.ensure_chunks(first, last, read_end)?;
876        if !need_fetch {
877            self.cache_hits += 1;
878        }
879
880        // Capacity capped so a forged huge length cannot abort on allocation.
881        let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
882        let mut remaining = length as usize;
883        let mut cursor = offset;
884        while remaining > 0 {
885            let chunk_index = cursor / self.chunk_size;
886            let chunk_offset = (cursor % self.chunk_size) as usize;
887            let chunk = self.chunks.get(&chunk_index).expect("chunk fetched above");
888            if chunk_offset >= chunk.len() {
889                return Err(MdfError::TooShortBuffer {
890                    actual: chunk.len(),
891                    expected: chunk_offset + 1,
892                    file: file!(),
893                    line: line!(),
894                });
895            }
896            let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
897            out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
898            cursor += take as u64;
899            remaining -= take;
900            if take == 0 {
901                break;
902            }
903        }
904
905        if out.len() != length as usize {
906            return Err(MdfError::TooShortBuffer {
907                actual: out.len(),
908                expected: length as usize,
909                file: file!(),
910                line: line!(),
911            });
912        }
913
914        Ok(out)
915    }
916}
917
918/// HTTP range-request reader using the synchronous [`ureq`] client.
919///
920/// Each [`ByteRangeReader::read_range`] call issues a single
921/// `Range: bytes=A-B` GET request and expects an HTTP 206 response. The
922/// underlying `ureq::Agent` is reused across calls so TCP keep-alive applies.
923///
924/// Wrap this in [`CachingRangeReader`] when building an index, otherwise the
925/// many small metadata reads will each become a separate round-trip.
926#[cfg(feature = "http")]
927pub struct HttpRangeReader {
928    agent: ureq::Agent,
929    url: String,
930    request_count: u64,
931    /// Size the resource must have (the size an index was built from). Every
932    /// ranged response reports the resource's total size in `Content-Range`;
933    /// a different total means the file behind the URL was replaced, and is
934    /// refused instead of decoding bytes at offsets meant for another file.
935    expected_size: Option<u64>,
936}
937
938#[cfg(feature = "http")]
939impl HttpRangeReader {
940    pub fn new(url: impl Into<String>) -> Result<Self, MdfError> {
941        Ok(Self {
942            agent: shared_http_agent()?,
943            url: url.into(),
944            request_count: 0,
945            expected_size: None,
946        })
947    }
948
949    /// Require every response to report a resource of `size` bytes (see
950    /// [`MdfError::InvalidArgument`] for the mismatch error).
951    pub fn expect_size(&mut self, size: u64) {
952        self.expected_size = Some(size);
953    }
954
955    /// Fetch several byte ranges concurrently (up to
956    /// [`MAX_PARALLEL_REQUESTS`] at a time) and return their bytes in order.
957    ///
958    /// Used by the batched read driver ([`MdfIndex`]'s URL reads): a round of
959    /// a time-window search needs a few dozen small, independent ranges, and
960    /// fetching them one after another would cost one round-trip each.
961    pub(crate) fn read_ranges_parallel(&mut self, spans: &[(u64, u64)]) -> Result<Vec<Vec<u8>>, MdfError> {
962        if spans.len() <= 1 {
963            return spans.iter().map(|&(o, l)| self.read_range(o, l)).collect();
964        }
965        let (agent, url, expected) = (&self.agent, self.url.as_str(), self.expected_size);
966        let mut out: Vec<Vec<u8>> = Vec::with_capacity(spans.len());
967        for chunk in spans.chunks(MAX_PARALLEL_REQUESTS) {
968            let results: Vec<Result<Vec<u8>, MdfError>> = std::thread::scope(|scope| {
969                let handles: Vec<_> = chunk
970                    .iter()
971                    .map(|&(offset, length)| scope.spawn(move || http_get_range(agent, url, offset, length, expected)))
972                    .collect();
973                handles
974                    .into_iter()
975                    .map(|h| {
976                        h.join().unwrap_or_else(|_| {
977                            Err(MdfError::BlockSerializationError("HTTP fetch thread panicked".to_string()))
978                        })
979                    })
980                    .collect()
981            });
982            self.request_count += chunk.len() as u64;
983            for r in results {
984                out.push(r?);
985            }
986        }
987        Ok(out)
988    }
989
990    /// Download the whole resource with one plain `GET`.
991    pub(crate) fn fetch_all(&mut self) -> Result<Vec<u8>, MdfError> {
992        use std::io::Read;
993        self.request_count += 1;
994        let (agent, url) = (&self.agent, self.url.as_str());
995        with_retries(|| {
996            let response = agent.get(url).call().map_err(classify_call_error)?;
997            let mut body = Vec::new();
998            response
999                .into_reader()
1000                .read_to_end(&mut body)
1001                .map_err(|e| HttpFailure::Transient(MdfError::IOError(e), None))?;
1002            Ok(body)
1003        })
1004    }
1005
1006    /// Learn the resource's total size with a single-byte ranged GET.
1007    ///
1008    /// Uses `GET` with `Range: bytes=0-0` and parses the total length out of
1009    /// the `Content-Range: bytes 0-0/<total>` header, rather than issuing a
1010    /// `HEAD`. Presigned URLs (e.g. AWS S3) are signed for one specific HTTP
1011    /// method, so a `HEAD` against a GET-signed URL is rejected with 403; a
1012    /// ranged `GET` matches the method the data reads use.
1013    pub fn probe_size(&mut self) -> Result<u64, MdfError> {
1014        use std::io::Read;
1015
1016        let (agent, url) = (&self.agent, self.url.as_str());
1017        let resp = with_retries(|| agent.get(url).set("Range", "bytes=0-0").call().map_err(classify_call_error))?;
1018        self.request_count += 1;
1019
1020        // Preferred: total size from the Content-Range header of a 206 response.
1021        let total = resp
1022            .header("Content-Range")
1023            .and_then(|cr| cr.rsplit('/').next().map(|s| s.trim().to_string()))
1024            .filter(|s| s != "*")
1025            .and_then(|s| s.parse::<u64>().ok());
1026
1027        // Fallback: a server that ignores the Range header replies 200 with the
1028        // full body, in which case Content-Length is the total size. Drain the
1029        // body so the connection can be reused for keep-alive.
1030        let content_length = resp
1031            .header("Content-Length")
1032            .and_then(|s| s.parse::<u64>().ok());
1033        let status = resp.status();
1034        let mut sink = Vec::new();
1035        let _ = resp.into_reader().take(1).read_to_end(&mut sink);
1036
1037        if let Some(len) = total {
1038            Ok(len)
1039        } else if status == 200 {
1040            content_length.ok_or_else(|| {
1041                MdfError::BlockSerializationError(
1042                    "size probe: server ignored Range and sent no Content-Length".into(),
1043                )
1044            })
1045        } else {
1046            Err(MdfError::BlockSerializationError(
1047                "size probe: 206 response missing Content-Range total".into(),
1048            ))
1049        }
1050    }
1051
1052    /// Total number of HTTP requests issued by this reader.
1053    pub fn request_count(&self) -> u64 {
1054        self.request_count
1055    }
1056}
1057
1058#[cfg(feature = "http")]
1059impl ByteRangeReader for HttpRangeReader {
1060    type Error = MdfError;
1061
1062    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
1063        let bytes = http_get_range(&self.agent, &self.url, offset, length, self.expected_size);
1064        if length > 0 {
1065            self.request_count += 1;
1066        }
1067        bytes
1068    }
1069}
1070
1071/// Maximum concurrent range requests issued by
1072/// [`HttpRangeReader::read_ranges_parallel`].
1073#[cfg(feature = "http")]
1074pub(crate) const MAX_PARALLEL_REQUESTS: usize = 8;
1075
1076/// The process-wide HTTP agent shared by every [`HttpRangeReader`].
1077///
1078/// Building a TLS connector loads the system trust store, and each agent has
1079/// its own connection pool, so a fresh agent per read meant a fresh TCP + TLS
1080/// handshake for every `read()` / `values()` call. One shared agent keeps
1081/// connections alive across calls (and across indexes reading the same host).
1082#[cfg(feature = "http")]
1083fn shared_http_agent() -> Result<ureq::Agent, MdfError> {
1084    // Keyed by process id: a forked child (multiprocessing, DataLoader
1085    // workers) must not reuse the parent's pooled keep-alive sockets, or
1086    // several processes would interleave requests on one TCP stream.
1087    static AGENT: std::sync::Mutex<Option<(u32, ureq::Agent)>> = std::sync::Mutex::new(None);
1088    let pid = std::process::id();
1089    let mut slot = AGENT.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1090    if let Some((owner, agent)) = slot.as_ref()
1091        && *owner == pid
1092    {
1093        return Ok(agent.clone());
1094    }
1095    // ureq's native-tls feature is not auto-wired (unlike rustls): the
1096    // connector must be constructed and attached explicitly, otherwise
1097    // HTTPS requests fail with "no TLS backend is configured".
1098    let connector = native_tls::TlsConnector::new().map_err(|e| {
1099        MdfError::BlockSerializationError(format!("failed to init TLS backend: {e}"))
1100    })?;
1101    let agent = ureq::AgentBuilder::new()
1102        .tls_connector(std::sync::Arc::new(connector))
1103        .max_idle_connections_per_host(MAX_PARALLEL_REQUESTS)
1104        // Without a read timeout a stalled connection would block a read
1105        // (and the Python caller) forever; a timed-out attempt is retried.
1106        .timeout_connect(HTTP_CONNECT_TIMEOUT)
1107        .timeout_read(HTTP_READ_TIMEOUT)
1108        .timeout_write(HTTP_READ_TIMEOUT)
1109        .build();
1110    *slot = Some((pid, agent.clone()));
1111    Ok(agent)
1112}
1113
1114/// Time allowed to establish a connection.
1115#[cfg(feature = "http")]
1116const HTTP_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
1117
1118/// Longest wait for the next bytes of a response (a stall, not a slow
1119/// download: every socket read restarts it).
1120#[cfg(feature = "http")]
1121const HTTP_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
1122
1123/// Retries of a request that failed transiently (connection error, timeout,
1124/// `408` / `429` / `5xx`) before giving up.
1125#[cfg(feature = "http")]
1126const HTTP_MAX_RETRIES: u32 = 3;
1127
1128/// Delay before the first retry; doubled for each further one.
1129#[cfg(feature = "http")]
1130const HTTP_RETRY_BASE_DELAY: std::time::Duration = std::time::Duration::from_millis(200);
1131
1132/// Upper bound on a single retry delay, including a server's `Retry-After`.
1133#[cfg(feature = "http")]
1134const HTTP_MAX_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(10);
1135
1136/// Outcome of one failed HTTP attempt.
1137#[cfg(feature = "http")]
1138enum HttpFailure {
1139    /// Worth retrying (connection error, timeout, throttling, server
1140    /// error), optionally after the delay the server asked for.
1141    Transient(MdfError, Option<std::time::Duration>),
1142    /// Retrying would not help (`404`, `403`, a wrong range, a replaced file).
1143    Fatal(MdfError),
1144}
1145
1146/// Statuses that signal a temporary condition: request timeout, throttling
1147/// (S3 `503 SlowDown`, `429`) and server/gateway errors.
1148#[cfg(feature = "http")]
1149fn is_transient_status(status: u16) -> bool {
1150    matches!(status, 408 | 429 | 500 | 502 | 503 | 504)
1151}
1152
1153/// A `Retry-After: <seconds>` header (the HTTP-date form is ignored).
1154#[cfg(feature = "http")]
1155fn retry_after(resp: &ureq::Response) -> Option<std::time::Duration> {
1156    resp.header("Retry-After")?.trim().parse::<u64>().ok().map(std::time::Duration::from_secs)
1157}
1158
1159/// Classify a failed `call()`: connection/IO errors and transient statuses
1160/// are retried; every other status and transport error is final.
1161#[cfg(feature = "http")]
1162fn classify_call_error(error: ureq::Error) -> HttpFailure {
1163    match error {
1164        ureq::Error::Status(status, resp) if is_transient_status(status) => {
1165            let after = retry_after(&resp);
1166            HttpFailure::Transient(
1167                MdfError::BlockSerializationError(format!("HTTP request failed with status {status}")),
1168                after,
1169            )
1170        }
1171        ureq::Error::Status(status, _) => {
1172            HttpFailure::Fatal(MdfError::BlockSerializationError(format!("HTTP request failed with status {status}")))
1173        }
1174        ureq::Error::Transport(transport) => {
1175            let error = MdfError::BlockSerializationError(format!("HTTP request failed: {transport}"));
1176            // A dropped or refused connection is worth another try; a bad
1177            // URL, an unknown host or a proxy misconfiguration is not.
1178            match transport.kind() {
1179                ureq::ErrorKind::ConnectionFailed | ureq::ErrorKind::Io | ureq::ErrorKind::ProxyConnect => {
1180                    HttpFailure::Transient(error, None)
1181                }
1182                _ => HttpFailure::Fatal(error),
1183            }
1184        }
1185    }
1186}
1187
1188/// Run `attempt` until it succeeds, fails for good, or has been retried
1189/// [`HTTP_MAX_RETRIES`] times, sleeping with exponential backoff (or the
1190/// server's `Retry-After`, capped) between attempts.
1191#[cfg(feature = "http")]
1192fn with_retries<T>(mut attempt: impl FnMut() -> Result<T, HttpFailure>) -> Result<T, MdfError> {
1193    let mut delay = HTTP_RETRY_BASE_DELAY;
1194    let mut retries = 0;
1195    loop {
1196        match attempt() {
1197            Ok(value) => return Ok(value),
1198            Err(HttpFailure::Fatal(e)) => return Err(e),
1199            Err(HttpFailure::Transient(e, after)) => {
1200                if retries == HTTP_MAX_RETRIES {
1201                    return Err(match e {
1202                        MdfError::BlockSerializationError(msg) => MdfError::BlockSerializationError(format!(
1203                            "{msg} (gave up after {} attempts)",
1204                            HTTP_MAX_RETRIES + 1
1205                        )),
1206                        other => other,
1207                    });
1208                }
1209                std::thread::sleep(after.unwrap_or(delay).min(HTTP_MAX_RETRY_DELAY));
1210                delay *= 2;
1211                retries += 1;
1212            }
1213        }
1214    }
1215}
1216
1217/// Total size from a `Content-Range: bytes A-B/<total>` (or `bytes */<total>`)
1218/// header, if it states one.
1219#[cfg(feature = "http")]
1220fn content_range_total(header: Option<&str>) -> Option<u64> {
1221    header?.rsplit_once('/')?.1.trim().parse().ok()
1222}
1223
1224/// `(A, B)` from a `Content-Range: bytes A-B/<total>` header.
1225#[cfg(feature = "http")]
1226fn content_range_span(header: Option<&str>) -> Option<(u64, u64)> {
1227    let spec = header?.trim().strip_prefix("bytes")?.trim();
1228    let (a, b) = spec.split_once('/')?.0.split_once('-')?;
1229    Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
1230}
1231
1232/// Refuse a source whose size differs from the one the index was built from.
1233#[cfg(any(feature = "http", not(target_arch = "wasm32")))]
1234fn check_resource_size(source: &str, expected: u64, actual: u64) -> Result<(), MdfError> {
1235    if expected != 0 && actual != expected {
1236        return Err(MdfError::InvalidArgument(format!(
1237            "the source does not match the index: the index was built from a {expected}-byte \
1238             file but '{source}' is {actual} bytes — attach the file the index was built \
1239             from, or rebuild the index"
1240        )));
1241    }
1242    Ok(())
1243}
1244
1245/// One `Range: bytes=A-B` GET of `[offset, offset + length)`, retried on
1246/// transient failures (see [`with_retries`]).
1247#[cfg(feature = "http")]
1248fn http_get_range(
1249    agent: &ureq::Agent,
1250    url: &str,
1251    offset: u64,
1252    length: u64,
1253    expected_size: Option<u64>,
1254) -> Result<Vec<u8>, MdfError> {
1255    if length == 0 {
1256        return Ok(Vec::new());
1257    }
1258    with_retries(|| http_get_range_once(agent, url, offset, length, expected_size))
1259}
1260
1261/// A single attempt of [`http_get_range`].
1262#[cfg(feature = "http")]
1263fn http_get_range_once(
1264    agent: &ureq::Agent,
1265    url: &str,
1266    offset: u64,
1267    length: u64,
1268    expected_size: Option<u64>,
1269) -> Result<Vec<u8>, HttpFailure> {
1270    use std::io::Read;
1271    use HttpFailure::Fatal;
1272
1273    let range_header = format!("bytes={}-{}", offset, offset + length - 1);
1274    let resp = match agent.get(url).set("Range", &range_header).call() {
1275        Ok(resp) => resp,
1276        // 416: the range starts past the end of the resource. Its
1277        // `Content-Range: bytes */<size>` tells whether the file shrank.
1278        Err(ureq::Error::Status(416, resp)) => {
1279            let total = content_range_total(resp.header("Content-Range"));
1280            if let (Some(expected), Some(actual)) = (expected_size, total) {
1281                check_resource_size(url, expected, actual).map_err(Fatal)?;
1282            }
1283            return Err(Fatal(MdfError::BlockSerializationError(format!(
1284                "HTTP range {offset}..{} is past the end of {url}{}",
1285                offset + length,
1286                total.map(|t| format!(" ({t} bytes)")).unwrap_or_default()
1287            ))));
1288        }
1289        Err(e) => return Err(classify_call_error(e)),
1290    };
1291    if let (Some(expected), Some(actual)) = (expected_size, content_range_total(resp.header("Content-Range"))) {
1292        check_resource_size(url, expected, actual).map_err(Fatal)?;
1293    }
1294    // A 206 must carry exactly the requested range: a proxy or a shared
1295    // connection that answers with other bytes of the right length would
1296    // otherwise be decoded silently.
1297    if resp.status() == 206 {
1298        if let Some((start, end)) = content_range_span(resp.header("Content-Range")) {
1299            let want_end = offset + length - 1;
1300            // (A shorter range at end-of-file is caught by the short-body check below.)
1301            if start != offset || end > want_end {
1302                return Err(Fatal(MdfError::BlockSerializationError(format!(
1303                    "HTTP server returned bytes {start}-{end} for requested range {offset}-{want_end}"
1304                ))));
1305            }
1306        }
1307    }
1308
1309    // 206 Partial Content is the accepted path. A 200 means the server
1310    // ignored the Range header and sent the whole resource: that is only
1311    // usable when the requested range starts at offset 0 (the body can be
1312    // truncated to `length`); for any other offset the first `length`
1313    // bytes would silently come from the wrong position, so error out.
1314    let status = resp.status();
1315    match status {
1316        206 => {}
1317        200 => {
1318            if offset != 0 {
1319                return Err(Fatal(MdfError::BlockSerializationError(format!(
1320                    "HTTP server ignored Range request (status 200) for offset {}; \
1321                     refusing to return bytes from the wrong position",
1322                    offset
1323                ))));
1324            }
1325        }
1326        other => {
1327            return Err(Fatal(MdfError::BlockSerializationError(format!(
1328                "HTTP range request returned unexpected status {other}"
1329            ))));
1330        }
1331    }
1332
1333    // Read at most `length` bytes (a 200 response carries the whole
1334    // resource and must be truncated), then insist we actually received
1335    // all of them: a short body must be an error, not silently fewer
1336    // records. Capacity is capped so a forged huge length cannot abort
1337    // on allocation.
1338    let mut buf = Vec::with_capacity(length.min(1 << 20) as usize);
1339    // A connection reset or read timeout mid-body is transient.
1340    resp.into_reader()
1341        .take(length)
1342        .read_to_end(&mut buf)
1343        .map_err(|e| HttpFailure::Transient(MdfError::IOError(e), None))?;
1344    if (buf.len() as u64) < length {
1345        // Report absolute positions so wrappers (e.g. CachingRangeReader)
1346        // can learn the resource's true end from `actual`.
1347        return Err(Fatal(MdfError::TooShortBuffer {
1348            actual: (offset + buf.len() as u64) as usize,
1349            expected: (offset + length) as usize,
1350            file: file!(),
1351            line: line!(),
1352        }));
1353    }
1354    Ok(buf)
1355}
1356
1357impl MdfIndex {
1358    /// Create an index from an MDF file on disk.
1359    ///
1360    /// Not available on `wasm32-unknown-unknown`; use [`from_bytes`](Self::from_bytes) instead.
1361    #[cfg(not(target_arch = "wasm32"))]
1362    pub fn from_file(file_path: &str) -> Result<Self, MdfError> {
1363        let mdf = Mdf::from_file(file_path)?;
1364        let file_size = std::fs::metadata(file_path)
1365            .map_err(MdfError::IOError)?
1366            .len();
1367        let mut index = Self::build_index(mdf, file_size)?;
1368        index.source = Some(Source::File(file_path.to_string()));
1369        Ok(index)
1370    }
1371
1372    /// Build an index from an MDF file served over HTTP / S3 using range
1373    /// requests, remembering the URL as the index's [`Source`].
1374    ///
1375    /// Only metadata blocks are fetched while building; sample data is read
1376    /// lazily on [`MdfIndex::read`]. Requires the `http` feature.
1377    #[cfg(feature = "http")]
1378    pub fn from_url(url: &str) -> Result<Self, MdfError> {
1379        Self::from_url_with_chunk_size(url, 1 << 20)
1380    }
1381
1382    /// [`MdfIndex::from_url`] with an explicit metadata read-ahead chunk size.
1383    #[cfg(feature = "http")]
1384    pub fn from_url_with_chunk_size(url: &str, chunk_size: u64) -> Result<Self, MdfError> {
1385        let mut http = HttpRangeReader::new(url)?;
1386        let file_size = http.probe_size()?;
1387        let mut cached = CachingRangeReader::with_chunk_size(http, chunk_size);
1388        cached.set_known_size(file_size);
1389        let mut index = Self::from_range_reader(&mut cached, file_size)?;
1390        index.source = Some(Source::Url(url.to_string()));
1391        Ok(index)
1392    }
1393
1394    /// Shared index-building logic operating on an already-parsed [`MDF`].
1395    fn build_index(mdf: Mdf, file_size: u64) -> Result<Self, MdfError> {
1396        let start_time_ns = mdf.start_time_ns();
1397        let mut indexed_groups = Vec::new();
1398        // (own ##CG address, remote master ##CG address) per group.
1399        let mut cg_links: Vec<(u64, u64)> = Vec::new();
1400
1401        for group in mdf.channel_groups() {
1402            let raw_cg = group.raw_channel_group();
1403            cg_links.push((raw_cg.addr, raw_cg.block.master_cg_addr));
1404            // Unsorted data groups (a record-ID prefix with several channel
1405            // groups sharing the same data blocks) would make every CG index
1406            // the same interleaved records as if they were all its own.
1407            let raw_dg = group.raw_data_group();
1408            if raw_dg.block.record_id_len > 0 && raw_dg.channel_groups.len() > 1 {
1409                return Err(MdfError::BlockSerializationError(
1410                    "unsorted data groups (record IDs with multiple channel groups) \
1411                     are not supported by the index"
1412                        .to_string(),
1413                ));
1414            }
1415
1416            let mut indexed_channels = Vec::new();
1417            let mmap = group.mmap();
1418
1419            for channel in group.channels() {
1420                let block = channel.block();
1421
1422                let resolved_conversion = if let Some(mut conversion) = block.conversion.clone() {
1423                    if let Err(e) = conversion.resolve_all_dependencies(mmap) {
1424                        eprintln!("Warning: Failed to resolve conversion dependencies for channel '{}': {}",
1425                                 block.name.as_deref().unwrap_or("<unnamed>"), e);
1426                    }
1427                    Some(conversion)
1428                } else {
1429                    None
1430                };
1431
1432                let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
1433                    let mut slice_reader = BorrowedSliceReader { data: mmap };
1434                    Self::extract_vlsd_data_blocks(&mut slice_reader, block.data)?
1435                } else {
1436                    Vec::new()
1437                };
1438
1439                indexed_channels.push(IndexedChannel {
1440                    name: channel.name()?,
1441                    unit: channel.unit()?,
1442                    comment: channel.comment()?,
1443                    data_type: block.data_type.clone(),
1444                    byte_offset: block.byte_offset,
1445                    bit_offset: block.bit_offset,
1446                    bit_count: block.bit_count,
1447                    channel_type: block.channel_type,
1448                    flags: block.flags,
1449                    pos_invalidation_bit: block.pos_invalidation_bit,
1450                    conversion: resolved_conversion,
1451                    conversion_addr: block.conversion_addr,
1452                    vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
1453                        Some(block.data)
1454                    } else {
1455                        None
1456                    },
1457                    vlsd_data_blocks,
1458                });
1459            }
1460
1461            let data_blocks = Self::extract_data_blocks(&group)?;
1462
1463            indexed_groups.push(IndexedChannelGroup {
1464                name: group.name()?,
1465                comment: group.comment()?,
1466                record_id_len: group.raw_data_group().block.record_id_len,
1467                record_size: group.raw_channel_group().block.samples_byte_nr,
1468                invalidation_bytes: group.raw_channel_group().block.invalidation_bytes_nr,
1469                record_count: group.raw_channel_group().block.cycles_nr,
1470                channels: indexed_channels,
1471                data_blocks,
1472                master_group: None,
1473            });
1474        }
1475        Self::link_remote_masters(&mut indexed_groups, &cg_links);
1476
1477        Ok(MdfIndex { file_size, start_time_ns, channel_groups: indexed_groups, source: None })
1478    }
1479
1480    /// Fill [`IndexedChannelGroup::master_group`] for groups without a local
1481    /// master whose `##CG` carries an MDF 4.2 remote-master link.
1482    fn link_remote_masters(groups: &mut [IndexedChannelGroup], cg_links: &[(u64, u64)]) {
1483        for g in 0..groups.len() {
1484            let target = cg_links[g].1;
1485            if target == 0 || groups[g].master_channel().is_some() {
1486                continue;
1487            }
1488            groups[g].master_group = cg_links
1489                .iter()
1490                .position(|&(addr, _)| addr == target)
1491                .filter(|&m| m != g && groups[m].master_channel().is_some());
1492        }
1493    }
1494
1495    /// Extract data block information from a channel group.
1496    ///
1497    /// The same bounds-checked, cycle-checked walk as a range-reader build
1498    /// (over the in-memory file), reading every fragment header: a
1499    /// truncated file is an error, not a panic.
1500    fn extract_data_blocks(group: &crate::api::channel_group::ChannelGroup) -> Result<Vec<DataBlockInfo>, MdfError> {
1501        let mut reader = BorrowedSliceReader { data: group.mmap() };
1502        Self::extract_data_blocks_via_reader(&mut reader, group.raw_data_group().block.data_block_addr, None, 0)
1503    }
1504
1505    /// Create an index from an in-memory MDF byte buffer.
1506    ///
1507    /// This is the primary constructor on `wasm32-unknown-unknown`.
1508    pub fn from_bytes(data: Vec<u8>) -> Result<Self, MdfError> {
1509        let file_size = data.len() as u64;
1510        let mdf = Mdf::from_bytes(data)?;
1511        Self::build_index(mdf, file_size)
1512    }
1513
1514    /// Build an [`MdfIndex`] using only [`ByteRangeReader`] calls.
1515    ///
1516    /// Issues range reads for the file's metadata structures (identification,
1517    /// header, data groups, channel groups, channels, text and conversion
1518    /// blocks, and data-block headers) but never reads the sample data
1519    /// itself. Intended for remote sources such as HTTP-served files; wrap
1520    /// the underlying reader in [`CachingRangeReader`] to keep the number of
1521    /// underlying requests low.
1522    ///
1523    /// `file_size` is stored on the resulting index for use by later byte-range
1524    /// calculations. Callers should obtain it from a HEAD request (e.g.
1525    /// [`HttpRangeReader::probe_size`]) or other out-of-band metadata.
1526    pub fn from_range_reader<R>(
1527        reader: &mut R,
1528        file_size: u64,
1529    ) -> Result<Self, MdfError>
1530    where
1531        R: ByteRangeReader<Error = MdfError>,
1532    {
1533        use crate::parsing::reader_walk;
1534
1535        let walk = reader_walk::walk(reader)?;
1536
1537        let start_time_ns = if walk.header.abs_time == 0 {
1538            None
1539        } else {
1540            Some(walk.header.abs_time)
1541        };
1542
1543        let mut indexed_groups = Vec::with_capacity(walk.groups.len());
1544        let cg_links: Vec<(u64, u64)> =
1545            walk.groups.iter().map(|g| (g.cg_addr, g.cg.master_cg_addr)).collect();
1546        for group in walk.groups {
1547            let mut indexed_channels = Vec::with_capacity(group.channels.len());
1548            for ch in group.channels {
1549                let block = ch.block;
1550                let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
1551                    Self::extract_vlsd_data_blocks(reader, block.data)?
1552                } else {
1553                    Vec::new()
1554                };
1555                indexed_channels.push(IndexedChannel {
1556                    name: ch.name,
1557                    unit: ch.unit,
1558                    comment: ch.comment,
1559                    data_type: block.data_type.clone(),
1560                    byte_offset: block.byte_offset,
1561                    bit_offset: block.bit_offset,
1562                    bit_count: block.bit_count,
1563                    channel_type: block.channel_type,
1564                    flags: block.flags,
1565                    pos_invalidation_bit: block.pos_invalidation_bit,
1566                    // Remote / range-reader builds defer conversion resolution:
1567                    // only the block's location is recorded here; it is fetched
1568                    // and resolved lazily on the first value read.
1569                    conversion: None,
1570                    conversion_addr: ch.conversion_addr,
1571                    vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
1572                        Some(block.data)
1573                    } else {
1574                        None
1575                    },
1576                    vlsd_data_blocks,
1577                });
1578            }
1579
1580            // Bytes of record data the group holds, so equal-length ##DL
1581            // lists can be sized without touching the data region.
1582            let expected_bytes = group.cg.cycles_nr.checked_mul(
1583                group.record_id_len as u64
1584                    + group.cg.samples_byte_nr as u64
1585                    + group.cg.invalidation_bytes_nr as u64,
1586            );
1587            let data_blocks = Self::extract_data_blocks_via_reader(
1588                reader,
1589                group.data_block_addr,
1590                expected_bytes,
1591                file_size,
1592            )?;
1593
1594            indexed_groups.push(IndexedChannelGroup {
1595                name: group.cg_name,
1596                comment: group.cg_comment,
1597                record_id_len: group.record_id_len,
1598                record_size: group.cg.samples_byte_nr,
1599                invalidation_bytes: group.cg.invalidation_bytes_nr,
1600                record_count: group.cg.cycles_nr,
1601                channels: indexed_channels,
1602                data_blocks,
1603                master_group: None,
1604            });
1605        }
1606        Self::link_remote_masters(&mut indexed_groups, &cg_links);
1607
1608        Ok(MdfIndex {
1609            file_size,
1610            start_time_ns,
1611            channel_groups: indexed_groups,
1612            source: None,
1613        })
1614    }
1615
1616    /// Mirror of [`Self::extract_data_blocks`] that fetches headers via a
1617    /// [`ByteRangeReader`] instead of slicing into a memory map.
1618    ///
1619    /// When `reader.is_probing()` (an incremental gap-discovery pass — see
1620    /// [`ByteRangeReader::is_probing`]), a failed read stops walking this
1621    /// group's data-block chain and returns what was collected so far instead
1622    /// of propagating the error: the reader has already recorded the miss, so
1623    /// the caller can fetch it and retry. The resulting index is **partial**
1624    /// and must be discarded while any reader miss remains — this is exactly
1625    /// the batched gap-discovery contract `MdfIndex::from_range_reader`
1626    /// callers (`buildIndexStep`/`IndexBuilder::step`) already enforce by only
1627    /// reporting `done` once a pass records zero misses. On-demand readers
1628    /// (the default `is_probing() == false`) are unaffected: a failed read is
1629    /// still fatal, exactly as before.
1630    ///
1631    /// For an **equal-length** `##DL` list (`dl_flags` bit 0) reached directly
1632    /// from the data group, the fragment sizes follow from the list itself:
1633    /// every fragment but the last holds `dl_equal_length` bytes and the last
1634    /// holds the rest of `expected_bytes` (cycle count × record size). When
1635    /// that arithmetic is consistent with the number of fragments and the file
1636    /// size, the fragment headers are **not read** — on a column-oriented file
1637    /// whose metadata sits at the front this keeps the whole index build inside
1638    /// the metadata prefix (one or two requests, independent of the number of
1639    /// data blocks). Reads still verify each fragment header they fetch. Any
1640    /// inconsistency falls back to reading the headers.
1641    fn extract_data_blocks_via_reader<R>(
1642        reader: &mut R,
1643        data_block_addr: u64,
1644        expected_bytes: Option<u64>,
1645        file_size: u64,
1646    ) -> Result<Vec<DataBlockInfo>, MdfError>
1647    where
1648        R: ByteRangeReader<Error = MdfError>,
1649    {
1650        let mut data_blocks = Vec::new();
1651
1652        // Read a range, but when probing and the read fails, stop walking
1653        // this chain and hand back what's been collected so far rather than
1654        // aborting the whole build.
1655        macro_rules! probe_read {
1656            ($offset:expr, $len:expr) => {
1657                match reader.read_range($offset, $len) {
1658                    Ok(b) => b,
1659                    Err(e) => {
1660                        if reader.is_probing() {
1661                            return Ok(data_blocks);
1662                        }
1663                        return Err(e);
1664                    }
1665                }
1666            };
1667        }
1668
1669        let mut current_block_address = data_block_addr;
1670        let mut visited = std::collections::HashSet::new();
1671
1672        while current_block_address != 0 {
1673            if !visited.insert(current_block_address) {
1674                return Err(MdfError::BlockLinkError(format!(
1675                    "cycle detected in data block chain at address {:#x}",
1676                    current_block_address
1677                )));
1678            }
1679            let header_bytes = probe_read!(current_block_address, 24);
1680            let block_header =
1681                crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;
1682
1683            match block_header.id.as_str() {
1684                "##DT" | "##DV" => {
1685                    data_blocks.push(DataBlockInfo {
1686                        file_offset: current_block_address,
1687                        size: block_header.block_len,
1688                        is_compressed: false,
1689                    });
1690                    current_block_address = 0;
1691                }
1692                "##DZ" => {
1693                    data_blocks.push(DataBlockInfo {
1694                        file_offset: current_block_address,
1695                        size: block_header.block_len,
1696                        is_compressed: true,
1697                    });
1698                    current_block_address = 0;
1699                }
1700                "##DL" => {
1701                    let dl_bytes = probe_read!(current_block_address, block_header.block_len);
1702                    let data_list_block =
1703                        crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;
1704
1705                    if current_block_address == data_block_addr && data_list_block.next == 0
1706                        && let Some(derived) = Self::derive_equal_length_fragments(
1707                            &data_list_block,
1708                            expected_bytes,
1709                            file_size,
1710                        ) {
1711                            data_blocks.extend(derived);
1712                            break;
1713                        }
1714
1715                    for &fragment_address in &data_list_block.data_links {
1716                        if fragment_address == 0 {
1717                            continue; // NIL link (skipped by the in-memory reader too)
1718                        }
1719                        let frag_header_bytes = probe_read!(fragment_address, 24);
1720                        let fragment_header = crate::blocks::common::BlockHeader::from_bytes(
1721                            &frag_header_bytes,
1722                        )?;
1723                        let is_compressed = fragment_header.id == "##DZ";
1724                        data_blocks.push(DataBlockInfo {
1725                            file_offset: fragment_address,
1726                            size: fragment_header.block_len,
1727                            is_compressed,
1728                        });
1729                    }
1730
1731                    current_block_address = data_list_block.next;
1732                }
1733                unexpected_id => {
1734                    return Err(MdfError::BlockIDError {
1735                        actual: unexpected_id.to_string(),
1736                        expected: "##DT / ##DV / ##DL / ##DZ".to_string(),
1737                    });
1738                }
1739            }
1740        }
1741
1742        Ok(data_blocks)
1743    }
1744
1745    /// Fragment locations of an equal-length `##DL` derived without reading
1746    /// the fragments (see [`Self::extract_data_blocks_via_reader`]); `None`
1747    /// when the list is not equal-length or the numbers do not add up.
1748    fn derive_equal_length_fragments(
1749        dl: &crate::blocks::data_list_block::DataListBlock,
1750        expected_bytes: Option<u64>,
1751        file_size: u64,
1752    ) -> Option<Vec<DataBlockInfo>> {
1753        let equal = dl.data_block_len.filter(|_| dl.flags & 1 != 0)?;
1754        let total = expected_bytes?;
1755        let n = dl.data_links.len() as u64;
1756        if equal == 0 || n == 0 || total == 0 || dl.data_links.contains(&0) {
1757            return None;
1758        }
1759        // (n-1) full fragments plus a non-empty last one must hold exactly `total`.
1760        let full = (n - 1).checked_mul(equal)?;
1761        if total <= full || total > full.checked_add(equal)? {
1762            return None;
1763        }
1764        let last = total - full;
1765        let mut out: Vec<DataBlockInfo> = Vec::with_capacity(n as usize);
1766        for (i, &addr) in dl.data_links.iter().enumerate() {
1767            let data = if i as u64 + 1 == n { last } else { equal };
1768            let size = data.checked_add(24)?;
1769            if file_size > 0 && addr.checked_add(size)? > file_size {
1770                return None;
1771            }
1772            // Fragments must not overlap (ascending, each starting after the
1773            // previous one ends); anything else is left to the headers.
1774            if let Some(prev) = out.last()
1775                && addr < prev.file_offset.checked_add(prev.size)?
1776            {
1777                return None;
1778            }
1779            out.push(DataBlockInfo { file_offset: addr, size, is_compressed: false });
1780        }
1781        Some(out)
1782    }
1783
1784    /// Read the data sections of `blocks` in order, coalescing blocks that sit
1785    /// back to back in the file (at most 7 bytes of alignment padding apart)
1786    /// into a single read of up to [`MAX_COALESCED_READ`] bytes, and call `f`
1787    /// with each block's data section.
1788    ///
1789    /// A column-oriented file stores each signal's blocks contiguously, so a
1790    /// whole signal arrives in one range request instead of one per block.
1791    /// Every read starts at a block header, and each block's header is
1792    /// verified (`##DT`/`##DV`) before its data is decoded. The header's own
1793    /// length is authoritative: when it disagrees with the indexed size (e.g.
1794    /// fragment sizes derived from an equal-length `##DL` and a stale cycle
1795    /// count), the block's real data section is used — re-read if it extends
1796    /// beyond the coalesced read — so bytes beyond a block are never decoded.
1797    fn for_each_data_section<R, F>(
1798        reader: &mut R,
1799        blocks: &[DataBlockInfo],
1800        mut f: F,
1801    ) -> Result<(), MdfError>
1802    where
1803        R: ByteRangeReader<Error = MdfError>,
1804        F: FnMut(&[u8]) -> Result<(), MdfError>,
1805    {
1806        // With a probing reader every missing section is recorded in one
1807        // pass (sections after a miss are requested but not decoded), so a
1808        // batched read needs one round, not one per section.
1809        let mut first_err = None;
1810        let mut i = 0;
1811        while i < blocks.len() {
1812            let start = blocks[i].file_offset;
1813            Self::data_section_size(&blocks[i])?;
1814            let mut end = start.checked_add(blocks[i].size).ok_or_else(|| {
1815                MdfError::BlockSerializationError("data block offset overflows".to_string())
1816            })?;
1817            let mut j = i + 1;
1818            while j < blocks.len() {
1819                let b = &blocks[j];
1820                let b_end = b.file_offset.saturating_add(b.size);
1821                if b.file_offset < end
1822                    || b.file_offset - end > 7
1823                    || b.size < 24
1824                    || b_end - start > MAX_COALESCED_READ
1825                {
1826                    break;
1827                }
1828                end = b_end;
1829                j += 1;
1830            }
1831            let buf = match reader.read_range(start, end - start) {
1832                Ok(buf) if first_err.is_none() => buf,
1833                Ok(_) => {
1834                    i = j;
1835                    continue;
1836                }
1837                Err(e) if reader.is_probing() => {
1838                    first_err.get_or_insert(e);
1839                    i = j;
1840                    continue;
1841                }
1842                Err(e) => return Err(e),
1843            };
1844            for b in &blocks[i..j] {
1845                let header_start = (b.file_offset - start) as usize;
1846                let data_start = header_start + 24;
1847                let len = Self::verified_data_len(buf.get(header_start..data_start), b)?;
1848                match usize::try_from(len).ok().and_then(|l| buf.get(data_start..data_start.checked_add(l)?)) {
1849                    Some(data) => f(data)?,
1850                    None => f(&reader.read_range(b.file_offset + 24, len)?)?,
1851                }
1852            }
1853            i = j;
1854        }
1855        match first_err {
1856            Some(e) => Err(e),
1857            None => Ok(()),
1858        }
1859    }
1860
1861    /// Check that `header` (the 24 header bytes of `block`, if available) is an
1862    /// uncompressed `##DT`/`##DV` block and return the length of its data
1863    /// section according to the header (which wins over the indexed size).
1864    fn verified_data_len(header: Option<&[u8]>, block: &DataBlockInfo) -> Result<u64, MdfError> {
1865        let h = BlockHeader::from_bytes(header.unwrap_or(&[]))?;
1866        if (h.id == "##DT" || h.id == "##DV") && h.block_len >= 24 {
1867            return Ok(h.block_len - 24);
1868        }
1869        Err(MdfError::BlockSerializationError(format!(
1870            "data block at offset {} is {} with length {} but the index expects an \
1871             uncompressed ##DT/##DV block of {} bytes (compressed or inconsistent \
1872             file; rebuild the index)",
1873            block.file_offset, h.id, h.block_len, block.size
1874        )))
1875    }
1876
1877    /// Walk a VLSD channel's `data` chain (a single `##SD`, or a `##DL` chain
1878    /// of `##SD`/`##DZ` fragments) and record each fragment's location in chain
1879    /// order.
1880    ///
1881    /// Generic over [`ByteRangeReader`] so the mmap path (via
1882    /// [`BorrowedSliceReader`]) and the remote path share one implementation.
1883    /// Cycle-detects the `##DL` `next` chain, rejects unexpected block IDs, and
1884    /// validates that a variable-length `##DL`'s per-fragment virtual offsets
1885    /// reproduce the running sum of prior fragments' data-section sizes — the
1886    /// invariant the offset-based reader relies on.
1887    ///
1888    /// When `reader.is_probing()`, a failed read stops walking this VLSD
1889    /// chain and returns what was collected so far instead of propagating the
1890    /// error — see the identical rationale on
1891    /// [`Self::extract_data_blocks_via_reader`]. Non-probing readers keep
1892    /// today's fatal-on-first-miss behavior.
1893    fn extract_vlsd_data_blocks<R>(
1894        reader: &mut R,
1895        data_addr: u64,
1896    ) -> Result<Vec<DataBlockInfo>, MdfError>
1897    where
1898        R: ByteRangeReader<Error = MdfError>,
1899    {
1900        let mut data_blocks: Vec<DataBlockInfo> = Vec::new();
1901
1902        // See `extract_data_blocks_via_reader`'s `probe_read!` for the
1903        // rationale: batched gap discovery skips an unreadable subtree
1904        // instead of aborting the whole pass, but only when probing.
1905        macro_rules! probe_read {
1906            ($offset:expr, $len:expr) => {
1907                match reader.read_range($offset, $len) {
1908                    Ok(b) => b,
1909                    Err(e) => {
1910                        if reader.is_probing() {
1911                            return Ok(data_blocks);
1912                        }
1913                        return Err(e);
1914                    }
1915                }
1916            };
1917        }
1918
1919        let mut visited: std::collections::HashSet<u64> = std::collections::HashSet::new();
1920        // Running sum of fragment data-section sizes (size - 24), i.e. the
1921        // virtual start offset of the next fragment in the concatenated stream.
1922        let mut running_offset: u64 = 0;
1923        let mut current = data_addr;
1924
1925        while current != 0 {
1926            let header_bytes = probe_read!(current, 24);
1927            let header = crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;
1928
1929            match header.id.as_str() {
1930                "##SD" => {
1931                    data_blocks.push(DataBlockInfo {
1932                        file_offset: current,
1933                        size: header.block_len,
1934                        is_compressed: false,
1935                    });
1936                    current = 0;
1937                }
1938                "##DZ" => {
1939                    data_blocks.push(DataBlockInfo {
1940                        file_offset: current,
1941                        size: header.block_len,
1942                        is_compressed: true,
1943                    });
1944                    current = 0;
1945                }
1946                "##DL" => {
1947                    // Cycle detection on the DL chain: a chain revisiting an
1948                    // address would otherwise loop forever.
1949                    if !visited.insert(current) {
1950                        return Err(MdfError::BlockLinkError(format!(
1951                            "cycle detected in VLSD data list chain at address {:#x}",
1952                            current
1953                        )));
1954                    }
1955                    let dl_bytes = probe_read!(current, header.block_len);
1956                    let dl = crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;
1957
1958                    for (i, &fragment_address) in dl.data_links.iter().enumerate() {
1959                        if fragment_address == 0 {
1960                            continue;
1961                        }
1962                        let frag_header_bytes = probe_read!(fragment_address, 24);
1963                        let frag_header =
1964                            crate::blocks::common::BlockHeader::from_bytes(&frag_header_bytes)?;
1965                        let is_compressed = match frag_header.id.as_str() {
1966                            "##SD" => false,
1967                            "##DZ" => true,
1968                            other => {
1969                                return Err(MdfError::BlockIDError {
1970                                    actual: other.to_string(),
1971                                    expected: "##SD / ##DZ".to_string(),
1972                                });
1973                            }
1974                        };
1975
1976                        // A variable-length DL carries an explicit virtual
1977                        // offset per fragment. The offset-based read path maps
1978                        // an inline offset to a fragment via cumulative
1979                        // data-section sizes, so a non-contiguous chain would
1980                        // silently mislocate entries — reject it here.
1981                        if let Some(offsets) = &dl.offsets
1982                            && let Some(&declared) = offsets.get(i)
1983                                && declared != running_offset {
1984                                    return Err(MdfError::BlockSerializationError(format!(
1985                                        "non-contiguous VLSD ##SD chain is unsupported: \
1986                                         fragment at offset {} declares virtual start {} \
1987                                         but the running data-section sum is {}",
1988                                        fragment_address, declared, running_offset
1989                                    )));
1990                                }
1991
1992                        let data_section = frag_header.block_len.checked_sub(24).ok_or_else(|| {
1993                            MdfError::BlockSerializationError(format!(
1994                                "VLSD fragment at offset {} has size {} \
1995                                 (smaller than the 24-byte block header)",
1996                                fragment_address, frag_header.block_len
1997                            ))
1998                        })?;
1999                        running_offset = running_offset.checked_add(data_section).ok_or_else(|| {
2000                            MdfError::BlockSerializationError(
2001                                "VLSD ##SD chain total size overflows the address space"
2002                                    .to_string(),
2003                            )
2004                        })?;
2005
2006                        data_blocks.push(DataBlockInfo {
2007                            file_offset: fragment_address,
2008                            size: frag_header.block_len,
2009                            is_compressed,
2010                        });
2011                    }
2012
2013                    current = dl.next;
2014                }
2015                other => {
2016                    return Err(MdfError::BlockIDError {
2017                        actual: other.to_string(),
2018                        expected: "##SD / ##DL / ##DZ".to_string(),
2019                    });
2020                }
2021            }
2022        }
2023
2024        Ok(data_blocks)
2025    }
2026
2027    /// Save the index to a JSON file.
2028    ///
2029    /// Not available on `wasm32-unknown-unknown`; use [`to_json`](Self::to_json) instead.
2030    #[cfg(not(target_arch = "wasm32"))]
2031    pub fn save(&self, index_path: &str) -> Result<(), MdfError> {
2032        let json = self.to_json()?;
2033        std::fs::write(index_path, json)
2034            .map_err(MdfError::IOError)?;
2035        Ok(())
2036    }
2037
2038    /// Load an index from a JSON file.
2039    ///
2040    /// Not available on `wasm32-unknown-unknown`; use [`from_json`](Self::from_json) instead.
2041    #[cfg(not(target_arch = "wasm32"))]
2042    pub fn load(index_path: &str) -> Result<Self, MdfError> {
2043        let json = std::fs::read_to_string(index_path)
2044            .map_err(MdfError::IOError)?;
2045        Self::from_json(&json)
2046    }
2047
2048    /// Serialize the index to a JSON string (available on all targets).
2049    pub fn to_json(&self) -> Result<String, MdfError> {
2050        serde_json::to_string_pretty(self)
2051            .map_err(|e| MdfError::BlockSerializationError(format!("JSON serialization failed: {}", e)))
2052    }
2053
2054    /// Deserialize an index from a JSON string (available on all targets).
2055    ///
2056    /// The deserialized index is [validated](Self::validate) so hostile or
2057    /// stale index data errors here instead of panicking later during reads.
2058    pub fn from_json(json: &str) -> Result<Self, MdfError> {
2059        let index: Self = serde_json::from_str(json)
2060            .map_err(|e| MdfError::BlockSerializationError(format!("JSON deserialization failed: {}", e)))?;
2061        index.validate()?;
2062        Ok(index)
2063    }
2064
2065    /// Validate structural invariants of the index.
2066    ///
2067    /// Called from [`Self::from_json`] / [`Self::load`] so that
2068    /// malformed (hostile or stale) index data returns an error instead of
2069    /// causing panics, integer underflow, or huge allocations during reads.
2070    pub fn validate(&self) -> Result<(), MdfError> {
2071        for group in &self.channel_groups {
2072            let group_name = group.name.as_deref().unwrap_or("<unnamed>");
2073            for db in &group.data_blocks {
2074                if db.size < 24 {
2075                    return Err(MdfError::BlockSerializationError(format!(
2076                        "invalid index: group '{}' data block at offset {} has size {} \
2077                         (smaller than the 24-byte block header)",
2078                        group_name, db.file_offset, db.size
2079                    )));
2080                }
2081                if db.file_offset.checked_add(db.size).is_none() {
2082                    return Err(MdfError::BlockSerializationError(format!(
2083                        "invalid index: group '{}' data block at offset {} with size {} \
2084                         overflows the file address space",
2085                        group_name, db.file_offset, db.size
2086                    )));
2087                }
2088            }
2089            if !group.data_blocks.is_empty() {
2090                Self::checked_record_size(group)?;
2091            }
2092            for channel in &group.channels {
2093                for db in &channel.vlsd_data_blocks {
2094                    if db.size < 24 {
2095                        return Err(MdfError::BlockSerializationError(format!(
2096                            "invalid index: group '{}' VLSD data block at offset {} has size {} \
2097                             (smaller than the 24-byte block header)",
2098                            group_name, db.file_offset, db.size
2099                        )));
2100                    }
2101                    if db.file_offset.checked_add(db.size).is_none() {
2102                        return Err(MdfError::BlockSerializationError(format!(
2103                            "invalid index: group '{}' VLSD data block at offset {} with size {} \
2104                             overflows the file address space",
2105                            group_name, db.file_offset, db.size
2106                        )));
2107                    }
2108                }
2109            }
2110        }
2111        Ok(())
2112    }
2113
2114    /// Total on-disk record size (record id + data + invalidation bytes) for
2115    /// a group, validated non-zero so callers can safely divide by it.
2116    fn checked_record_size(group: &IndexedChannelGroup) -> Result<usize, MdfError> {
2117        let size = group.record_id_len as usize
2118            + group.record_size as usize
2119            + group.invalidation_bytes as usize;
2120        if size == 0 {
2121            return Err(MdfError::BlockSerializationError(format!(
2122                "invalid index: channel group '{}' has record size 0",
2123                group.name.as_deref().unwrap_or("<unnamed>")
2124            )));
2125        }
2126        Ok(size)
2127    }
2128
2129    /// Size of a data block's data section (block size minus the 24-byte
2130    /// header), validated so a corrupt/forged block size cannot underflow.
2131    fn data_section_size(data_block: &DataBlockInfo) -> Result<u64, MdfError> {
2132        data_block.size.checked_sub(24).ok_or_else(|| {
2133            MdfError::BlockSerializationError(format!(
2134                "invalid index: data block at offset {} has size {} \
2135                 (smaller than the 24-byte block header)",
2136                data_block.file_offset, data_block.size
2137            ))
2138        })
2139    }
2140
2141    /// Error for VLSD channels on the byte-range calculation paths.
2142    ///
2143    /// A VLSD channel's fixed record field holds an 8-byte offset into a
2144    /// separate `##SD` stream, not the value bytes, so a static
2145    /// `(offset, length)` range cannot describe where a sample's payload
2146    /// lives. Value reads (`read` / `values`) resolve the indirection and are
2147    /// fully supported; only byte-range calculation refuses VLSD channels.
2148    fn ensure_not_vlsd(channel: &IndexedChannel) -> Result<(), MdfError> {
2149        if channel.channel_type == 1 {
2150            return Err(MdfError::BlockSerializationError(format!(
2151                "byte ranges cannot represent offset-indirected VLSD channel '{}'; \
2152                 use read()/values() instead",
2153                channel.name.as_deref().unwrap_or("<unnamed>")
2154            )));
2155        }
2156        Ok(())
2157    }
2158
2159    /// Read channel values using the index and a byte range reader.
2160    ///
2161    /// Internal positional helper — the public entry point is
2162    /// [`MdfReader::values`], which resolves channels by name.
2163    ///
2164    /// # Returns
2165    /// A vector of `Option<DecodedValue>` where:
2166    /// - `Some(value)` represents a valid decoded value
2167    /// - `None` represents an invalid value (invalidation bit set or decoding failed)
2168    pub(crate) fn read_channel_values<R: ByteRangeReader<Error = MdfError>>(
2169        &self,
2170        group_index: usize,
2171        channel_index: usize,
2172        raw: bool,
2173        reader: &mut R
2174    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2175        let group = self.channel_groups.get(group_index)
2176            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
2177        
2178        let channel = group.channels.get(channel_index)
2179            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
2180
2181        let conversion = Self::read_conversion(channel, reader, raw)?;
2182
2183        if channel.is_virtual() {
2184            return self.virtual_values(group, 0, group.record_count, conversion.as_deref());
2185        }
2186        if channel.channel_type == 1 {
2187            return self.read_vlsd_channel_values(group, channel, conversion.as_deref(), reader);
2188        }
2189
2190        // For regular channels, read from data blocks
2191        self.read_regular_channel_values(group, channel, conversion.as_deref(), reader)
2192    }
2193
2194    /// Values of a virtual channel (`cn_type` 3/6) for records
2195    /// `[start, start + count)`: the raw value is the record index, converted
2196    /// through the channel's conversion (MDF 4.1 §6.6.3).
2197    fn virtual_values(
2198        &self,
2199        group: &IndexedChannelGroup,
2200        start: u64,
2201        count: u64,
2202        conversion: Option<&ConversionBlock>,
2203    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2204        // Nothing is read for a virtual channel, so bound the record count by
2205        // stored data instead of trusting a possibly forged `record_count`:
2206        // the group's own data blocks, or — for a byte-less time group (the
2207        // virtual master `to_column_oriented` writes) — the largest
2208        // data-backed group using it as its remote master.
2209        let available = if !group.data_blocks.is_empty() {
2210            Self::stored_records(group)?
2211        } else {
2212            let me = self.channel_groups.iter().position(|g| std::ptr::eq(g, group));
2213            self.channel_groups
2214                .iter()
2215                .filter(|g| me.is_some() && g.master_group == me && !g.data_blocks.is_empty())
2216                .filter_map(|g| Self::stored_records(g).ok())
2217                .max()
2218                // Nothing stored to check against: trust the group.
2219                .unwrap_or(group.record_count)
2220        };
2221        match start.checked_add(count) {
2222            Some(end) if end <= available => {}
2223            _ => {
2224                return Err(MdfError::BlockSerializationError(format!(
2225                    "virtual channel read of {} records from {} exceeds the {} records the \
2226                     group's data holds (rebuild the index)",
2227                    count, start, available
2228                )))
2229            }
2230        }
2231        let mut values = Vec::with_capacity((count as usize).min(1 << 24));
2232        for i in start..start + count {
2233            let raw = DecodedValue::UnsignedInteger(i);
2234            values.push(Some(match conversion {
2235                Some(conv) => conv.apply_decoded(raw, &[])?,
2236                None => raw,
2237            }));
2238        }
2239        Ok(values)
2240    }
2241
2242    /// Read the samples of the channel at `(g, c)` for the record window
2243    /// `[start, start + count)` only.
2244    ///
2245    /// For a regular channel only the bytes of the window's records are read
2246    /// (one range per data block the window touches, plus that block's
2247    /// 24-byte header, which is verified). A VLSD channel is read in full and
2248    /// sliced, since its payloads sit in a separate stream.
2249    pub(crate) fn read_channel_values_window<R: ByteRangeReader<Error = MdfError>>(
2250        &self,
2251        g: usize,
2252        c: usize,
2253        start: u64,
2254        count: u64,
2255        raw: bool,
2256        reader: &mut R,
2257    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2258        let (group, channel) = self.group_and_channel(g, c)?;
2259        Self::check_window(group, start, count)?;
2260        let conversion = Self::read_conversion(channel, reader, raw)?;
2261        self.window_values(group, channel, conversion.as_deref(), start, count, reader)
2262    }
2263
2264    fn window_values<R: ByteRangeReader<Error = MdfError>>(
2265        &self,
2266        group: &IndexedChannelGroup,
2267        channel: &IndexedChannel,
2268        conversion: Option<&ConversionBlock>,
2269        start: u64,
2270        count: u64,
2271        reader: &mut R,
2272    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2273        if channel.is_virtual() {
2274            return self.virtual_values(group, start, count, conversion);
2275        }
2276        if channel.channel_type == 1 {
2277            return self.read_vlsd_window_values(group, channel, conversion, start, count, reader);
2278        }
2279        let record_size = Self::checked_record_size(group)?;
2280        let temp_cb = channel.to_decode_only_channel_block();
2281        let mut values = Vec::with_capacity((count as usize).min(1 << 24));
2282        Self::for_each_window_section(reader, group, record_size, start, count, |data| {
2283            Self::decode_records_to_values(data, record_size, group, conversion, &temp_cb, &mut values)
2284        })?;
2285        Ok(values)
2286    }
2287
2288    /// `f64` variant of [`window_values`](Self::window_values) (invalid or
2289    /// non-numeric samples are NaN).
2290    fn window_values_f64<R: ByteRangeReader<Error = MdfError>>(
2291        &self,
2292        group: &IndexedChannelGroup,
2293        channel: &IndexedChannel,
2294        conversion: Option<&ConversionBlock>,
2295        start: u64,
2296        count: u64,
2297        reader: &mut R,
2298    ) -> Result<Vec<f64>, MdfError> {
2299        if channel.is_virtual() || channel.channel_type == 1 {
2300            let vals = self.window_values(group, channel, conversion, start, count, reader)?;
2301            return Ok(Self::vlsd_values_to_f64(vals));
2302        }
2303        let record_size = Self::checked_record_size(group)?;
2304        let temp_cb = channel.to_decode_only_channel_block();
2305        let linear_coeffs = Self::get_linear_coeffs(conversion);
2306        let mut values = Vec::with_capacity((count as usize).min(1 << 24));
2307        Self::for_each_window_section(reader, group, record_size, start, count, |data| {
2308            Self::decode_records_to_f64(data, record_size, group, channel, conversion, &temp_cb, linear_coeffs, conversion.is_some(), &mut values)
2309        })?;
2310        Ok(values)
2311    }
2312
2313    /// Call `f` with the records `[start, start + count)` of `group` (each
2314    /// call a run of whole records).
2315    ///
2316    /// The group's data blocks form one byte stream, in which record `i`
2317    /// occupies bytes `[i·size, (i+1)·size)`: only the part of each block the
2318    /// window covers is read, and a record split between two blocks is
2319    /// reassembled.
2320    fn for_each_window_section<R, F>(
2321        reader: &mut R,
2322        group: &IndexedChannelGroup,
2323        record_size: usize,
2324        start: u64,
2325        count: u64,
2326        mut f: F,
2327    ) -> Result<(), MdfError>
2328    where
2329        R: ByteRangeReader<Error = MdfError>,
2330        F: FnMut(&[u8]) -> Result<(), MdfError>,
2331    {
2332        let size = record_size as u64;
2333        let overflow = || MdfError::BlockSerializationError("record window overflows".to_string());
2334        let window_start = start.checked_mul(size).ok_or_else(overflow)?;
2335        let window_end = start.checked_add(count).and_then(|e| e.checked_mul(size)).ok_or_else(overflow)?;
2336        let mut records = RecordCarry::new(record_size);
2337        // Stream offset of the current block's first data byte.
2338        let mut block_start = 0u64;
2339        // A probing reader (the wasm fragment driver) records every missing
2340        // block of the window in one pass instead of stopping at the first.
2341        let mut first_err = None;
2342        for block in &group.data_blocks {
2343            if block_start >= window_end {
2344                break;
2345            }
2346            if block.is_compressed {
2347                return Err(MdfError::BlockSerializationError(
2348                    "Compressed blocks not yet supported in index reader".to_string(),
2349                ));
2350            }
2351            let block_end = block_start.saturating_add(Self::data_section_size(block)?);
2352            let (from, to) = (window_start.max(block_start), window_end.min(block_end));
2353            if from < to {
2354                let rel = from - block_start;
2355                let len = to - from;
2356                // Verify the block header like the full read path does (the
2357                // header wins over the index): a window starting at the
2358                // block's first byte reads header and data in one request.
2359                let read = if rel == 0 {
2360                    reader.read_range(block.file_offset, 24 + len).map(|mut bytes| {
2361                        let data = bytes.split_off(24.min(bytes.len()));
2362                        (bytes, data)
2363                    })
2364                } else {
2365                    let header = reader.read_range(block.file_offset, 24);
2366                    let data = reader.read_range(block.file_offset + 24 + rel, len);
2367                    header.and_then(|h| data.map(|d| (h, d)))
2368                };
2369                match read {
2370                    Ok((header, data)) if first_err.is_none() => {
2371                        let real_len = Self::verified_data_len(Some(&header), block)?;
2372                        if rel + len > real_len || data.len() as u64 != len {
2373                            return Err(MdfError::BlockSerializationError(format!(
2374                                "data block at offset {} holds {} data bytes but the index \
2375                                 expects at least {} (inconsistent file; rebuild the index)",
2376                                block.file_offset, real_len, rel + len
2377                            )));
2378                        }
2379                        records.feed(&data, &mut f)?;
2380                    }
2381                    Ok(_) => {}
2382                    Err(e) if reader.is_probing() => {
2383                        first_err.get_or_insert(e);
2384                    }
2385                    Err(e) => return Err(e),
2386                }
2387            }
2388            block_start = block_end;
2389        }
2390        if let Some(e) = first_err {
2391            return Err(e);
2392        }
2393        if block_start < window_end {
2394            return Err(MdfError::BlockSerializationError(format!(
2395                "record window ending at {} exceeds the {} records held by the data blocks",
2396                start + count,
2397                block_start / size
2398            )));
2399        }
2400        Ok(())
2401    }
2402
2403    /// Records a whole read of `group` decodes (for pre-allocation); refuses
2404    /// compressed blocks, which the index reader cannot decode yet.
2405    fn whole_read_records(group: &IndexedChannelGroup) -> Result<usize, MdfError> {
2406        if group.data_blocks.iter().any(|b| b.is_compressed) {
2407            return Err(MdfError::BlockSerializationError(
2408                "Compressed blocks not yet supported in index reader".to_string(),
2409            ));
2410        }
2411        Ok(Self::stored_records(group)? as usize)
2412    }
2413
2414    /// Records held by a group's data blocks: the blocks form one byte
2415    /// stream (a record may straddle two of them); a trailing partial record
2416    /// does not count.
2417    fn stored_records(group: &IndexedChannelGroup) -> Result<u64, MdfError> {
2418        let record_size = Self::checked_record_size(group)?;
2419        let mut bytes = 0u64;
2420        for block in &group.data_blocks {
2421            bytes = bytes.saturating_add(Self::data_section_size(block)?);
2422        }
2423        Ok(bytes / record_size as u64)
2424    }
2425
2426    fn group_and_channel(&self, g: usize, c: usize) -> Result<(&IndexedChannelGroup, &IndexedChannel), MdfError> {
2427        let group = self.channel_groups.get(g)
2428            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
2429        let channel = group.channels.get(c)
2430            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
2431        Ok((group, channel))
2432    }
2433
2434    fn check_window(group: &IndexedChannelGroup, start: u64, count: u64) -> Result<(), MdfError> {
2435        match start.checked_add(count) {
2436            Some(end) if end <= group.record_count => Ok(()),
2437            _ => Err(MdfError::BlockSerializationError(format!(
2438                "record window starting at {} for {} records exceeds the group's {} records",
2439                start, count, group.record_count
2440            ))),
2441        }
2442    }
2443
2444    /// `(group, channel)` of the time axis for `(g, c)`: its master, or the
2445    /// channel itself when it *is* the master.
2446    fn time_axis_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
2447        match self.master_location(g, c) {
2448            Some(m) => Some(m),
2449            None => self.channel_groups.get(g)?.channels.get(c)?.is_master().then_some((g, c)),
2450        }
2451    }
2452
2453    /// Record window `(start, count)` of the group owning `(g, c)` whose
2454    /// master (time) values lie in `[t_start, t_end]` (either bound optional).
2455    ///
2456    /// The master must be non-decreasing, as MDF requires for a time master.
2457    /// It is searched rather than read (see [`search_time_window`], shared
2458    /// with the in-memory reader so both select the same records): each step reads 16
2459    /// single records, so a window is found in a handful of small reads
2460    /// (`log16(records)` rounds per bound). With a probing reader (the wasm
2461    /// fragment driver) both bounds' probes of a round are attempted before the
2462    /// first miss is returned, so every gap of the round is recorded at once.
2463    pub(crate) fn record_window_for_time<R: ByteRangeReader<Error = MdfError>>(
2464        &self,
2465        g: usize,
2466        c: usize,
2467        t_start: Option<f64>,
2468        t_end: Option<f64>,
2469        reader: &mut R,
2470    ) -> Result<(u64, u64), MdfError> {
2471        let (group, channel) = self.group_and_channel(g, c)?;
2472        let Some((mg, m)) = self.time_axis_location(g, c) else {
2473            // Same rule as the in-memory reader (`Mdf::record_window`): an
2474            // empty group selects nothing, otherwise a master is required.
2475            if group.record_count == 0 {
2476                return Ok((0, 0));
2477            }
2478            return Err(MdfError::InvalidArgument(format!(
2479                "channel '{}' has no master (time) channel; cannot select by time",
2480                channel.name.as_deref().unwrap_or_default()
2481            )));
2482        };
2483        let (mgroup, mchannel) = self.group_and_channel(mg, m)?;
2484        let n = group.record_count.min(mgroup.record_count);
2485        let conversion = Self::resolve_conversion(mchannel, reader)?;
2486        search_time_window(n, t_start, t_end, |i| {
2487            Ok(self.window_values_f64(mgroup, mchannel, conversion.as_deref(), i, 1, reader)?[0])
2488        })
2489    }
2490
2491    /// Resolve a channel's conversion for reading.
2492    ///
2493    /// Prefers a conversion already resolved into the index (local-file /
2494    /// in-memory builds, and older serialized indexes). Otherwise — the remote
2495    /// / range-reader build path, which records only
2496    /// [`IndexedChannel::conversion_addr`] — it fetches the `##CC` block and
2497    /// resolves its dependency chain through `reader`, exactly when the caller
2498    /// asks to read values. Returns `None` when the channel has no conversion.
2499    fn resolve_conversion<'c, R: ByteRangeReader<Error = MdfError>>(
2500        channel: &'c IndexedChannel,
2501        reader: &mut R,
2502    ) -> Result<Option<Cow<'c, ConversionBlock>>, MdfError> {
2503        if let Some(conv) = &channel.conversion {
2504            return Ok(Some(Cow::Borrowed(conv)));
2505        }
2506        if channel.conversion_addr == 0 {
2507            return Ok(None);
2508        }
2509        let addr = channel.conversion_addr;
2510        let header_bytes = reader.read_range(addr, 24)?;
2511        let header = BlockHeader::from_bytes(&header_bytes)?;
2512        if header.id != "##CC" {
2513            return Err(MdfError::BlockIDError {
2514                actual: header.id,
2515                expected: "##CC".to_string(),
2516            });
2517        }
2518        let full = reader.read_range(addr, header.block_len)?;
2519        let mut cc = ConversionBlock::from_bytes(&full)?;
2520        cc.resolve_all_dependencies_via_reader(reader, addr)?;
2521        Ok(Some(Cow::Owned(cc)))
2522    }
2523
2524    /// The conversion a read applies: none for a `raw` read (the stored
2525    /// values are wanted, so a deferred conversion is not even fetched),
2526    /// else [`resolve_conversion`](Self::resolve_conversion).
2527    fn read_conversion<'c, R: ByteRangeReader<Error = MdfError>>(
2528        channel: &'c IndexedChannel,
2529        reader: &mut R,
2530        raw: bool,
2531    ) -> Result<Option<Cow<'c, ConversionBlock>>, MdfError> {
2532        if raw {
2533            return Ok(None);
2534        }
2535        Self::resolve_conversion(channel, reader)
2536    }
2537
2538    /// Resolve the conversion of the channel at `(g, c)` using `reader`,
2539    /// following the same lazy rules as the read paths. Crate-visible so the
2540    /// wasm bindings can drive fragment-based conversion resolution: pointing a
2541    /// gap-reporting reader at this lets the JS side discover exactly which
2542    /// conversion-block byte ranges it must fetch before a fragment read.
2543    #[allow(dead_code)] // used by the wasm bindings (wasm feature)
2544    pub(crate) fn resolve_channel_conversion<R: ByteRangeReader<Error = MdfError>>(
2545        &self,
2546        g: usize,
2547        c: usize,
2548        reader: &mut R,
2549    ) -> Result<Option<ConversionBlock>, MdfError> {
2550        let channel = self
2551            .channel_groups
2552            .get(g)
2553            .and_then(|grp| grp.channels.get(c))
2554            .ok_or_else(|| {
2555                MdfError::BlockSerializationError("Invalid channel index".to_string())
2556            })?;
2557        Ok(Self::resolve_conversion(channel, reader)?.map(Cow::into_owned))
2558    }
2559
2560    /// Extract linear conversion coefficients (a, b) for inline application.
2561    fn get_linear_coeffs(conversion: Option<&ConversionBlock>) -> Option<(f64, f64)> {
2562        conversion.and_then(|conv| {
2563            if conv.cc_type == ConversionType::Linear && conv.cc_val.len() >= 2 {
2564                Some((conv.cc_val[0], conv.cc_val[1]))
2565            } else {
2566                None
2567            }
2568        })
2569    }
2570
2571    /// Read values for a regular (non-VLSD) channel using byte range reader
2572    fn read_regular_channel_values<R: ByteRangeReader<Error = MdfError>>(
2573        &self,
2574        group: &IndexedChannelGroup,
2575        channel: &IndexedChannel,
2576        conversion: Option<&ConversionBlock>,
2577        reader: &mut R,
2578    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2579        let record_size = Self::checked_record_size(group)?;
2580        let total_records = Self::whole_read_records(group)?;
2581        // Cap the pre-allocation: `total_records` derives from index-supplied
2582        // block sizes, and a forged value must not abort on allocation. The
2583        // vector still grows as needed; real reads fail earlier at the reader.
2584        let mut values = Vec::with_capacity(total_records.min(1 << 24));
2585        let temp_cb = channel.to_decode_only_channel_block();
2586
2587        // Records split between two blocks are reassembled.
2588        let mut records = RecordCarry::new(record_size);
2589        Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
2590            records.feed(block_data, |run| {
2591                Self::decode_records_to_values(run, record_size, group, conversion, &temp_cb, &mut values)
2592            })
2593        })?;
2594
2595        Ok(values)
2596    }
2597
2598    /// Read values for a VLSD channel (channel type 1) via a byte-range reader.
2599    ///
2600    /// The channel's fixed record field holds an 8-byte little-endian virtual
2601    /// offset into the concatenation of the `##SD` fragments' data sections;
2602    /// at that offset lives one `[u32 length][payload]` entry. This resolves
2603    /// each record's offset into the captured fragment chain and decodes the
2604    /// payload, preserving one value per record so [`Signal`] timestamps stay
2605    /// aligned and per-record invalidation can be honoured.
2606    fn read_vlsd_channel_values<R: ByteRangeReader<Error = MdfError>>(
2607        &self,
2608        group: &IndexedChannelGroup,
2609        channel: &IndexedChannel,
2610        conversion: Option<&ConversionBlock>,
2611        reader: &mut R,
2612    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2613        Self::check_vlsd_readable(group, channel)?;
2614
2615        // Fetch each SD fragment's data section, tracking each fragment's
2616        // virtual start offset in the concatenated stream.
2617        let mut fragments: Vec<Vec<u8>> = Vec::with_capacity(channel.vlsd_data_blocks.len());
2618        let mut frag_starts: Vec<u64> = Vec::with_capacity(channel.vlsd_data_blocks.len());
2619        let mut running: u64 = 0;
2620        for db in &channel.vlsd_data_blocks {
2621            let data_len = Self::data_section_size(db)?;
2622            let bytes = reader.read_range(db.file_offset + 24, data_len)?;
2623            frag_starts.push(running);
2624            running = running.checked_add(bytes.len() as u64).ok_or_else(|| {
2625                MdfError::BlockSerializationError(
2626                    "VLSD ##SD chain total size overflows the address space".to_string(),
2627                )
2628            })?;
2629            fragments.push(bytes);
2630        }
2631        let stream_len = running;
2632
2633        let record_size = Self::checked_record_size(group)?;
2634        let record_id_len = group.record_id_len as usize;
2635        let cg_data_bytes = group.record_size;
2636        let has_invalidation = group.invalidation_bytes > 0;
2637        let all_invalid = channel.flags & 0x1 != 0;
2638
2639        // A fixed-record channel block (data == 0) drives the validity check;
2640        // a separate VLSD block (data != 0) drives payload decoding.
2641        let validity_cb = channel.to_decode_only_channel_block();
2642        let mut payload_cb = channel.to_decode_only_channel_block();
2643        payload_cb.data = 1;
2644
2645        let total_records = Self::whole_read_records(group)?;
2646        let mut values = Vec::with_capacity(total_records.min(1 << 24));
2647
2648        // Records split between two blocks are reassembled.
2649        let mut records = RecordCarry::new(record_size);
2650        Self::for_each_data_section(reader, &group.data_blocks, |section| records.feed(section, |block_data| {
2651            let record_count = block_data.len() / record_size;
2652            for i in 0..record_count {
2653                let record = &block_data[i * record_size..(i + 1) * record_size];
2654
2655                if all_invalid
2656                    || (has_invalidation
2657                        && !check_value_validity(record, record_id_len, cg_data_bytes, &validity_cb))
2658                {
2659                    values.push(None);
2660                    continue;
2661                }
2662
2663                // The record's offset into the signal-data stream (read like
2664                // `Mdf` does: an unsigned field of the channel's bit count).
2665                let virtual_offset = vlsd_offset(&validity_cb, record, record_id_len)?;
2666
2667                if virtual_offset >= stream_len {
2668                    return Err(MdfError::BlockSerializationError(format!(
2669                        "VLSD inline offset {} is past the end of the {}-byte signal-data stream",
2670                        virtual_offset, stream_len
2671                    )));
2672                }
2673
2674                // Locate the fragment whose virtual span contains the offset.
2675                let frag_idx = frag_starts.partition_point(|&s| s <= virtual_offset) - 1;
2676                let frag = &fragments[frag_idx];
2677                let pos = (virtual_offset - frag_starts[frag_idx]) as usize;
2678
2679                if pos + 4 > frag.len() {
2680                    return Err(MdfError::BlockSerializationError(format!(
2681                        "VLSD entry at virtual offset {} is truncated: no room for its \
2682                         length prefix in fragment {}",
2683                        virtual_offset, frag_idx
2684                    )));
2685                }
2686                let len = u32::from_le_bytes(frag[pos..pos + 4].try_into().unwrap()) as usize;
2687                let start = pos + 4;
2688                let end = match start.checked_add(len) {
2689                    Some(e) if e <= frag.len() => e,
2690                    _ => {
2691                        return Err(MdfError::BlockSerializationError(format!(
2692                            "VLSD entry at virtual offset {} declares length {} which \
2693                             exceeds fragment {} (size {})",
2694                            virtual_offset, len, frag_idx, frag.len()
2695                        )));
2696                    }
2697                };
2698                let payload = &frag[start..end];
2699
2700                if let Some(value) = decode_channel_value(payload, 0, &payload_cb) {
2701                    let final_value = if let Some(conversion) = conversion {
2702                        conversion.apply_decoded(value, &[])?
2703                    } else {
2704                        value
2705                    };
2706                    values.push(Some(final_value));
2707                } else {
2708                    values.push(None);
2709                }
2710            }
2711            Ok(())
2712        }))?;
2713
2714        Ok(values)
2715    }
2716
2717    /// Refuse VLSD channels the index reader cannot decode (compressed
2718    /// fragments, missing signal data). The offset field is checked per
2719    /// valid record, as `Mdf` does.
2720    fn check_vlsd_readable(group: &IndexedChannelGroup, channel: &IndexedChannel) -> Result<(), MdfError> {
2721        // Compressed fragments (either the fixed records or the SD stream) are
2722        // not decodable yet.
2723        if group.data_blocks.iter().any(|b| b.is_compressed)
2724            || channel.vlsd_data_blocks.iter().any(|b| b.is_compressed)
2725        {
2726            return Err(MdfError::BlockSerializationError(
2727                "Compressed blocks not yet supported in index reader".to_string(),
2728            ));
2729        }
2730
2731        // A VLSD channel without a data link has no signal data at all —
2732        // rebuilding the index cannot help, so distinguish it from an index
2733        // built before VLSD chains were captured.
2734        if channel.vlsd_data_blocks.is_empty() {
2735            if channel.vlsd_data_address.is_none() {
2736                return Err(MdfError::BlockSerializationError(format!(
2737                    "VLSD channel '{}' has no signal data (its ##SD data link is 0)",
2738                    channel.name.as_deref().unwrap_or("<unnamed>")
2739                )));
2740            }
2741            return Err(MdfError::BlockSerializationError(format!(
2742                "VLSD channel '{}' has no signal-data fragments recorded in the index; \
2743                 rebuild the index with this version to read it",
2744                channel.name.as_deref().unwrap_or("<unnamed>")
2745            )));
2746        }
2747
2748        // The offset field itself is read per valid record (`vlsd_offset`,
2749        // as `Mdf` does): an unusable field only fails a read that needs it.
2750        Ok(())
2751    }
2752
2753    /// Window read of a VLSD channel: decode only records
2754    /// `[start, start + count)`, fetching their inline offsets and then just
2755    /// the slice of the signal-data stream those offsets point into (one
2756    /// read, plus one more if the last entry runs past it) — not the whole
2757    /// stream.
2758    fn read_vlsd_window_values<R: ByteRangeReader<Error = MdfError>>(
2759        &self,
2760        group: &IndexedChannelGroup,
2761        channel: &IndexedChannel,
2762        conversion: Option<&ConversionBlock>,
2763        start: u64,
2764        count: u64,
2765        reader: &mut R,
2766    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2767        Self::check_vlsd_readable(group, channel)?;
2768        let record_size = Self::checked_record_size(group)?;
2769        let record_id_len = group.record_id_len as usize;
2770        let has_invalidation = group.invalidation_bytes > 0;
2771        let all_invalid = channel.flags & 0x1 != 0;
2772        let validity_cb = channel.to_decode_only_channel_block();
2773        let mut payload_cb = channel.to_decode_only_channel_block();
2774        payload_cb.data = 1;
2775
2776        // Inline offsets of the window's records (None = invalid sample).
2777        let mut offsets: Vec<Option<u64>> = Vec::with_capacity((count as usize).min(1 << 24));
2778        Self::for_each_window_section(reader, group, record_size, start, count, |data| {
2779            for record in data.chunks_exact(record_size) {
2780                if all_invalid
2781                    || (has_invalidation
2782                        && !check_value_validity(record, record_id_len, group.record_size, &validity_cb))
2783                {
2784                    offsets.push(None);
2785                    continue;
2786                }
2787                offsets.push(Some(vlsd_offset(&validity_cb, record, record_id_len)?));
2788            }
2789            Ok(())
2790        })?;
2791
2792        // Virtual start of each ##SD fragment in the concatenated stream.
2793        let mut frag_starts = Vec::with_capacity(channel.vlsd_data_blocks.len());
2794        let mut stream_len = 0u64;
2795        for db in &channel.vlsd_data_blocks {
2796            frag_starts.push(stream_len);
2797            stream_len = stream_len.checked_add(Self::data_section_size(db)?).ok_or_else(|| {
2798                MdfError::BlockSerializationError("VLSD ##SD chain total size overflows the address space".to_string())
2799            })?;
2800        }
2801        let present = || offsets.iter().flatten().copied();
2802        let (Some(lo), Some(hi)) = (present().min(), present().max()) else {
2803            return Ok(vec![None; offsets.len()]);
2804        };
2805        let prefix_end = hi.checked_add(4).filter(|&e| e <= stream_len).ok_or_else(|| {
2806            MdfError::BlockSerializationError(format!(
2807                "VLSD inline offset {hi} leaves no room for a length prefix in the {stream_len}-byte signal-data stream"
2808            ))
2809        })?;
2810        let mut buf = Self::read_vlsd_stream(reader, channel, &frag_starts, lo, prefix_end - lo)?;
2811        let entry_len = |buf: &[u8], off: u64| -> usize {
2812            let p = (off - lo) as usize;
2813            u32::from_le_bytes(buf[p..p + 4].try_into().unwrap()) as usize
2814        };
2815        let end = present().map(|off| off + 4 + entry_len(&buf, off) as u64).max().unwrap_or(prefix_end);
2816        if end > stream_len {
2817            return Err(MdfError::BlockSerializationError(format!(
2818                "VLSD entry ending at virtual offset {end} is past the end of the {stream_len}-byte signal-data stream"
2819            )));
2820        }
2821        if end > prefix_end {
2822            let more = Self::read_vlsd_stream(reader, channel, &frag_starts, prefix_end, end - prefix_end)?;
2823            buf.extend_from_slice(&more);
2824        }
2825
2826        let mut values = Vec::with_capacity(offsets.len());
2827        for off in &offsets {
2828            let Some(off) = *off else {
2829                values.push(None);
2830                continue;
2831            };
2832            // Like the full read, refuse an entry that does not fit in the
2833            // ##SD fragment it starts in.
2834            let frag_idx = frag_starts.partition_point(|&s| s <= off) - 1;
2835            let frag_end = frag_starts.get(frag_idx + 1).copied().unwrap_or(stream_len);
2836            let len = entry_len(&buf, off);
2837            if off + 4 + len as u64 > frag_end {
2838                return Err(MdfError::BlockSerializationError(format!(
2839                    "VLSD entry at virtual offset {} declares length {} which exceeds fragment {} (size {})",
2840                    off,
2841                    len,
2842                    frag_idx,
2843                    frag_end - frag_starts[frag_idx]
2844                )));
2845            }
2846            let p = (off - lo) as usize + 4;
2847            let payload = &buf[p..p + entry_len(&buf, off)];
2848            values.push(match decode_channel_value(payload, 0, &payload_cb) {
2849                Some(value) => Some(match conversion {
2850                    Some(conversion) => conversion.apply_decoded(value, &[])?,
2851                    None => value,
2852                }),
2853                None => None,
2854            });
2855        }
2856        Ok(values)
2857    }
2858
2859    /// Bytes `[from, from + len)` of a VLSD channel's concatenated
2860    /// signal-data stream, read from the ##SD fragments they fall in.
2861    fn read_vlsd_stream<R: ByteRangeReader<Error = MdfError>>(
2862        reader: &mut R,
2863        channel: &IndexedChannel,
2864        frag_starts: &[u64],
2865        from: u64,
2866        len: u64,
2867    ) -> Result<Vec<u8>, MdfError> {
2868        let to = from + len;
2869        let mut out = Vec::with_capacity(len as usize);
2870        // Attempt every fragment's read before failing, so a probing reader
2871        // records all gaps in one pass.
2872        let mut first_err = None;
2873        for (db, &fs) in channel.vlsd_data_blocks.iter().zip(frag_starts) {
2874            let fe = fs + Self::data_section_size(db)?;
2875            let (a, b) = (from.max(fs), to.min(fe));
2876            if a >= b {
2877                continue;
2878            }
2879            match reader.read_range(db.file_offset + 24 + (a - fs), b - a) {
2880                // A custom reader that returns fewer bytes (e.g. clamped at
2881                // EOF) must surface as an error, not an out-of-bounds slice.
2882                Ok(bytes) if bytes.len() as u64 != b - a => {
2883                    return Err(MdfError::TooShortBuffer {
2884                        actual: bytes.len(),
2885                        expected: (b - a) as usize,
2886                        file: file!(),
2887                        line: line!(),
2888                    });
2889                }
2890                Ok(bytes) => out.extend_from_slice(&bytes),
2891                Err(e) if reader.is_probing() => {
2892                    first_err.get_or_insert(e);
2893                }
2894                Err(e) => return Err(e),
2895            }
2896        }
2897        if let Some(e) = first_err {
2898            return Err(e);
2899        }
2900        Ok(out)
2901    }
2902
2903    /// Map VLSD decoded values to `f64`, matching `Channel::values`:
2904    /// numeric variants convert, everything else (strings, bytes, invalid) is
2905    /// NaN.
2906    fn vlsd_values_to_f64(values: Vec<Option<DecodedValue>>) -> Vec<f64> {
2907        values
2908            .into_iter()
2909            .map(|v| match v {
2910                Some(DecodedValue::Float(f)) => f,
2911                Some(DecodedValue::UnsignedInteger(u)) => u as f64,
2912                Some(DecodedValue::SignedInteger(i)) => i as f64,
2913                _ => f64::NAN,
2914            })
2915            .collect()
2916    }
2917
2918    /// Decode records from a data block slice into values vec.
2919    /// Shared by both the reader-based and slice-based paths.
2920    fn decode_records_to_values(
2921        block_data: &[u8],
2922        record_size: usize,
2923        group: &IndexedChannelGroup,
2924        conversion: Option<&ConversionBlock>,
2925        temp_cb: &crate::blocks::channel_block::ChannelBlock,
2926        values: &mut Vec<Option<DecodedValue>>,
2927    ) -> Result<(), MdfError> {
2928        if record_size == 0 {
2929            return Err(MdfError::BlockSerializationError(
2930                "invalid index: record size is 0".to_string(),
2931            ));
2932        }
2933        // Callers pass whole records (`RecordCarry` reassembles split ones).
2934        if !block_data.len().is_multiple_of(record_size) {
2935            return Err(MdfError::BlockSerializationError(format!(
2936                "internal error: {} bytes are not a whole number of {}-byte records",
2937                block_data.len(),
2938                record_size
2939            )));
2940        }
2941        let record_count = block_data.len() / record_size;
2942        let record_id_len = group.record_id_len as usize;
2943        let cg_data_bytes = group.record_size;
2944
2945        for i in 0..record_count {
2946            let record = &block_data[i * record_size..(i + 1) * record_size];
2947            if let Some(decoded) = decode_channel_value_with_validity(
2948                record, record_id_len, cg_data_bytes, temp_cb,
2949            ) {
2950                if decoded.is_valid {
2951                    let final_value = if let Some(conversion) = conversion {
2952                        conversion.apply_decoded(decoded.value, &[])?
2953                    } else {
2954                        decoded.value
2955                    };
2956                    values.push(Some(final_value));
2957                } else {
2958                    values.push(None);
2959                }
2960            } else {
2961                values.push(None);
2962            }
2963        }
2964        Ok(())
2965    }
2966
2967    /// Decode records from a data block as f64 values.
2968    /// Uses the fast decode_f64_from_record path and applies conversions inline.
2969    /// For channels without invalidation bytes, skips validity checking entirely.
2970    fn decode_records_to_f64(
2971        block_data: &[u8],
2972        record_size: usize,
2973        group: &IndexedChannelGroup,
2974        channel: &IndexedChannel,
2975        conversion: Option<&ConversionBlock>,
2976        temp_cb: &crate::blocks::channel_block::ChannelBlock,
2977        linear_coeffs: Option<(f64, f64)>,
2978        has_conversion: bool,
2979        values: &mut Vec<f64>,
2980    ) -> Result<(), MdfError> {
2981        if record_size == 0 {
2982            return Err(MdfError::BlockSerializationError(
2983                "invalid index: record size is 0".to_string(),
2984            ));
2985        }
2986        // Callers pass whole records (`RecordCarry` reassembles split ones).
2987        if !block_data.len().is_multiple_of(record_size) {
2988            return Err(MdfError::BlockSerializationError(format!(
2989                "internal error: {} bytes are not a whole number of {}-byte records",
2990                block_data.len(),
2991                record_size
2992            )));
2993        }
2994        let record_count = block_data.len() / record_size;
2995        let record_id_len = group.record_id_len as usize;
2996        let cg_data_bytes = group.record_size;
2997        let has_invalidation = group.invalidation_bytes > 0;
2998
2999        // MDF 4.1: cn_flags bit 0 ("all values invalid") applies regardless
3000        // of whether the group carries invalidation bytes. Short-circuit to
3001        // NaN for every sample, matching decode_records_to_values.
3002        if channel.flags & 0x1 != 0 {
3003            values.extend(std::iter::repeat_n(f64::NAN, record_count));
3004            return Ok(());
3005        }
3006
3007        // Each record is decoded once: straight to f64 (with a linear
3008        // conversion applied inline), or through `DecodedValue` when a
3009        // non-linear conversion needs it.
3010        let valid = |record: &[u8]| {
3011            !has_invalidation || check_value_validity(record, record_id_len, cg_data_bytes, temp_cb)
3012        };
3013        let records = block_data.chunks_exact(record_size);
3014        match (linear_coeffs, conversion.filter(|_| has_conversion)) {
3015            (Some((a, b)), _) => {
3016                for record in records {
3017                    values.push(match valid(record) {
3018                        true => a + b * decode_f64_from_record(record, record_id_len, temp_cb),
3019                        false => f64::NAN,
3020                    });
3021                }
3022            }
3023            (None, Some(conversion)) => {
3024                for record in records {
3025                    let value = match valid(record) {
3026                        true => decode_channel_value(record, record_id_len, temp_cb),
3027                        false => None,
3028                    };
3029                    values.push(match value {
3030                        Some(value) => match conversion.apply_decoded(value, &[])? {
3031                            DecodedValue::Float(v) => v,
3032                            DecodedValue::UnsignedInteger(v) => v as f64,
3033                            DecodedValue::SignedInteger(v) => v as f64,
3034                            _ => f64::NAN,
3035                        },
3036                        None => f64::NAN,
3037                    });
3038                }
3039            }
3040            (None, None) => {
3041                for record in records {
3042                    values.push(match valid(record) {
3043                        true => decode_f64_from_record(record, record_id_len, temp_cb),
3044                        false => f64::NAN,
3045                    });
3046                }
3047            }
3048        }
3049        Ok(())
3050    }
3051
3052    // ----- metadata (cross-language contract) -----------------------------
3053
3054    /// Metadata of every channel group, in file order.
3055    ///
3056    /// The raw indexed structures (record layout, data-block locations) are
3057    /// available through the public [`channel_groups`](Self::channel_groups)
3058    /// field.
3059    pub fn groups(&self) -> Result<Vec<GroupInfo>, MdfError> {
3060        Ok((0..self.channel_groups.len()).map(|g| self.group_info(g)).collect())
3061    }
3062
3063    /// Metadata of the first channel group named `name`, or `None`.
3064    ///
3065    /// The groups of a column-oriented (MDF 4.2) file are merged back into
3066    /// their source group, as [`Mdf::group`] does.
3067    pub fn group(&self, name: &str) -> Result<Option<GroupInfo>, MdfError> {
3068        let names = self.group_names();
3069        let Some(first) = names.iter().position(|n| n.as_deref() == Some(name)) else {
3070            return Ok(None);
3071        };
3072        let channel_counts: Vec<usize> = self.channel_groups.iter().map(|g| g.channels.len()).collect();
3073        let members = logical_group_members(&names, &self.time_groups(), &channel_counts, first);
3074        Ok(Some(merge_group_infos(
3075            self.group_info(first),
3076            members.iter().map(|&m| self.group_info(m)),
3077        )))
3078    }
3079
3080    fn group_names(&self) -> Vec<Option<String>> {
3081        self.channel_groups.iter().map(|g| g.name.clone()).collect()
3082    }
3083
3084    /// For each group, the group holding its time axis: itself for a local
3085    /// master, the remote master group of an MDF 4.2 column-oriented group,
3086    /// `None` when untimed.
3087    fn time_groups(&self) -> Vec<Option<usize>> {
3088        (0..self.channel_groups.len()).map(|g| self.time_group(g)).collect()
3089    }
3090
3091    fn time_group(&self, g: usize) -> Option<usize> {
3092        let group = self.channel_groups.get(g)?;
3093        if group.master_channel().is_some() {
3094            return Some(g);
3095        }
3096        group
3097            .master_group
3098            .filter(|&m| m != g && self.channel_groups.get(m).is_some_and(|mg| mg.master_channel().is_some()))
3099    }
3100
3101    /// Metadata of the first channel named `name`, or `None`. Pass `group` to
3102    /// look only in the group(s) with that name.
3103    pub fn channel(&self, name: &str, group: Option<&str>) -> Result<Option<ChannelInfo>, MdfError> {
3104        Ok(self.indexed_channel(name, group).map(IndexedChannel::info))
3105    }
3106
3107    /// Names of every named channel across all groups (duplicates kept).
3108    pub fn channel_names(&self) -> Result<Vec<String>, MdfError> {
3109        Ok(self
3110            .channel_groups
3111            .iter()
3112            .flat_map(|g| g.channels.iter())
3113            .filter_map(|c| c.name.clone())
3114            .collect())
3115    }
3116
3117    /// Measurement start time in nanoseconds since the Unix epoch, or `None`
3118    /// if the file header does not record one.
3119    pub fn start_time_ns(&self) -> Option<u64> {
3120        self.start_time_ns
3121    }
3122
3123    /// Size in bytes of the indexed MDF file.
3124    pub fn file_size(&self) -> u64 {
3125        self.file_size
3126    }
3127
3128    /// The raw [`IndexedChannel`] of the first channel named `name` (in the
3129    /// group(s) named `group`, when given). Rust-only access to the record
3130    /// layout behind [`channel`](Self::channel).
3131    pub fn indexed_channel(&self, name: &str, group: Option<&str>) -> Option<&IndexedChannel> {
3132        let (g, c) = self.locate_opt(name, group)?;
3133        self.channel_groups.get(g)?.channels.get(c)
3134    }
3135
3136    fn group_info(&self, g: usize) -> GroupInfo {
3137        let group = &self.channel_groups[g];
3138        GroupInfo {
3139            name: group.name.clone(),
3140            comment: group.comment.clone(),
3141            record_count: group.record_count,
3142            channel_names: group.channels.iter().filter_map(|c| c.name.clone()).collect(),
3143            // A column-oriented (MDF 4.2) signal group reports the shared
3144            // time channel it references.
3145            master_channel: group
3146                .master_channel()
3147                .or_else(|| {
3148                    group
3149                        .master_group
3150                        .and_then(|mg| self.channel_groups.get(mg))
3151                        .and_then(|mg| mg.master_channel())
3152                })
3153                .and_then(|c| c.name.clone()),
3154            channels: group.channels.iter().map(IndexedChannel::info).collect(),
3155        }
3156    }
3157
3158    /// Position of a channel by name, optionally restricted to a group name.
3159    pub(crate) fn locate_opt(&self, name: &str, group: Option<&str>) -> Option<(usize, usize)> {
3160        match group {
3161            Some(group) => self.locate_in(group, name),
3162            None => self.locate(name),
3163        }
3164    }
3165
3166    /// [`locate_opt`](Self::locate_opt), erroring with `ChannelNotFound`.
3167    pub(crate) fn locate_checked(&self, name: &str, group: Option<&str>) -> Result<(usize, usize), MdfError> {
3168        self.locate_opt(name, group)
3169            .ok_or_else(|| MdfError::channel_not_found(name, group))
3170    }
3171
3172    /// Resolve a channel name to its `(group_index, channel_index)` position.
3173    ///
3174    /// Returns the first match across all groups. Internal helper backing the
3175    /// name-based public methods.
3176    pub(crate) fn locate(&self, name: &str) -> Option<(usize, usize)> {
3177        for (g, group) in self.channel_groups.iter().enumerate() {
3178            for (c, channel) in group.channels.iter().enumerate() {
3179                if channel.name.as_deref() == Some(name) {
3180                    return Some((g, c));
3181                }
3182            }
3183        }
3184        None
3185    }
3186
3187    /// Resolve a `(group name, channel name)` pair to indices.
3188    ///
3189    /// Every group carrying that name is searched (a column-oriented file has
3190    /// one channel group per signal, all named after the source group), then
3191    /// the time groups they reference under another name — a time axis shared
3192    /// by several source groups carries only one of their names.
3193    pub(crate) fn locate_in(&self, group: &str, name: &str) -> Option<(usize, usize)> {
3194        let named: Vec<usize> = (0..self.channel_groups.len())
3195            .filter(|&g| self.channel_groups[g].name.as_deref() == Some(group))
3196            .collect();
3197        let remote = named
3198            .iter()
3199            .filter_map(|&g| self.time_group(g))
3200            .filter(|&t| self.channel_groups[t].name.as_deref() != Some(group));
3201        named.iter().copied().chain(remote).find_map(|g| {
3202            self.channel_groups[g]
3203                .channels
3204                .iter()
3205                .position(|ch| ch.name.as_deref() == Some(name))
3206                .map(|c| (g, c))
3207        })
3208    }
3209
3210    /// `(group, channel)` of the master (time) channel for the channel at
3211    /// `(g, c)`: the group's own master, or the remote master of an MDF 4.2
3212    /// column-oriented group. `None` when there is none or `(g, c)` is itself
3213    /// the master.
3214    pub(crate) fn master_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
3215        let grp = self.channel_groups.get(g)?;
3216        if let Some(m) = grp.channels.iter().position(|ch| ch.is_master()) {
3217            return (m != c).then_some((g, m));
3218        }
3219        let mg = grp.master_group?;
3220        let m = self.channel_groups.get(mg)?.channels.iter().position(|ch| ch.is_master())?;
3221        Some((mg, m))
3222    }
3223
3224    /// Bind this index to a byte-range source for reading sample data.
3225    ///
3226    /// The returned [`MdfReader`] borrows the index and owns `reader`; read
3227    /// values by channel name without re-supplying the source each time.
3228    pub fn open<R: ByteRangeReader<Error = MdfError>>(&self, reader: R) -> MdfReader<'_, R> {
3229        MdfReader { index: self, reader }
3230    }
3231
3232    /// Bind this index to a local file (via memory map) for reading.
3233    ///
3234    /// Convenience wrapper around [`MdfIndex::open`] using [`MmapRangeReader`].
3235    /// Not available on `wasm32-unknown-unknown`.
3236    #[cfg(not(target_arch = "wasm32"))]
3237    pub fn open_file(&self, path: &str) -> Result<MdfReader<'_, MmapRangeReader>, MdfError> {
3238        Ok(self.open(MmapRangeReader { mmap: self.map_source_file(path)? }))
3239    }
3240
3241    /// The data source `read` / `values` fetch sample bytes from, if any.
3242    pub fn source(&self) -> Option<&Source> {
3243        self.source.as_ref()
3244    }
3245
3246    /// Attach (or replace) the data source used by `read` / `values`.
3247    ///
3248    /// Accepts a [`Source`] or a string: `http(s)://` URLs are read with range
3249    /// requests (with the `http` feature), anything else is a file path.
3250    pub fn set_source(&mut self, source: impl Into<Source>) {
3251        self.source = Some(source.into());
3252    }
3253
3254    /// Detach the data source.
3255    pub fn clear_source(&mut self) {
3256        self.source = None;
3257    }
3258
3259    // ----- data (cross-language contract) ---------------------------------
3260
3261    /// Read a channel as a [`Signal`]: its values (conversions applied,
3262    /// `None` = invalid sample) paired with the group's time axis. For the
3263    /// master channel itself `timestamps` is empty.
3264    ///
3265    /// This is the lazy read path: bytes are fetched from the attached
3266    /// [`Source`] now, not at index build time. Errors with
3267    /// [`MdfError::ChannelNotFound`] if no such channel exists, or if no
3268    /// source is attached (see [`set_source`](Self::set_source)).
3269    ///
3270    /// `options` is `None` for the whole channel, or a [`ReadOptions`] with a
3271    /// group filter and/or a time or record window. A window fetches only the
3272    /// selected records: a time window is located by searching the master
3273    /// channel (a few single-record reads), not by downloading it.
3274    pub fn read<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
3275        let default = ReadOptions::default();
3276        let options = options.into().unwrap_or(&default);
3277        let window = options.window()?;
3278        let (g, c) = self.locate_checked(name, options.group_name())?;
3279        // Over a URL the channel and its time axis are fetched concurrently.
3280        #[cfg(feature = "http")]
3281        if let Source::Url(url) = self.require_source()? {
3282            let mut signals = self.read_many_url(url, &[(g, c)], window, options.raw)?;
3283            return signals.pop().ok_or_else(|| MdfError::BlockSerializationError("no signal read".to_string()));
3284        }
3285        if window == Window::All {
3286            return self.read_signal(g, c, options.raw);
3287        }
3288        let mut reader = self.source_reader(g, c, options.raw, true)?;
3289        let (start, count) = self.resolve_window_via(g, c, window, &mut reader)?;
3290        read_signal_window(self, g, c, start, count, options.raw, &mut reader)
3291    }
3292
3293    /// Read several channels at once, with the same `options` for all of
3294    /// them: one [`Signal`] per name, in the order given.
3295    ///
3296    /// Equivalent to calling [`read`](Self::read) for each name, but each
3297    /// time axis shared by several of the channels is fetched and decoded
3298    /// once (in a column-oriented file every signal of a source group shares
3299    /// one), a time window is searched once per time axis, and over a URL
3300    /// every byte range of the whole batch is fetched concurrently. Errors
3301    /// with [`MdfError::ChannelNotFound`] — before fetching anything — if any
3302    /// name is unknown.
3303    pub fn read_many<'o, S: AsRef<str>>(
3304        &self,
3305        names: &[S],
3306        options: impl Into<Option<&'o ReadOptions>>,
3307    ) -> Result<Vec<Signal>, MdfError> {
3308        let default = ReadOptions::default();
3309        let options = options.into().unwrap_or(&default);
3310        let window = options.window()?;
3311        let targets = self.locate_all(names, options.group_name())?;
3312        if targets.is_empty() {
3313            return Ok(Vec::new());
3314        }
3315        #[cfg(all(target_arch = "wasm32", not(feature = "http")))]
3316        let _ = window;
3317        match self.require_source()? {
3318            #[cfg(not(target_arch = "wasm32"))]
3319            Source::File(path) => {
3320                let mmap = self.map_source_file(path)?;
3321                if window == Window::All {
3322                    return self.read_many_from_slice(&targets, options.raw, &mmap);
3323                }
3324                self.read_many_at(&targets, window, options.raw, &mut MmapRangeReader { mmap })
3325            }
3326            #[cfg(target_arch = "wasm32")]
3327            Source::File(_) => Err(MdfError::BlockSerializationError(
3328                "file sources are not available on wasm32".to_string(),
3329            )),
3330            #[cfg(feature = "http")]
3331            Source::Url(url) => self.read_many_url(url, &targets, window, options.raw),
3332        }
3333    }
3334
3335    /// Read a numeric channel as plain `f64` values (no timestamps).
3336    /// Conversions are applied; invalid and non-numeric samples are `NaN`.
3337    /// `options` as for [`read`](Self::read).
3338    pub fn values<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
3339        let default = ReadOptions::default();
3340        let options = options.into().unwrap_or(&default);
3341        let window = options.window()?;
3342        let (g, c) = self.locate_checked(name, options.group_name())?;
3343        if window == Window::All {
3344            return self.read_values_f64_via_source(g, c, options.raw);
3345        }
3346        // Over a URL the window is located and fetched in batched rounds of
3347        // concurrent requests, as `read` does — not one block at a time.
3348        #[cfg(feature = "http")]
3349        if let Source::Url(url) = self.require_source()? {
3350            return self.values_window_url(url, g, c, window, options.raw, BATCH_MEMORY_LIMIT);
3351        }
3352        let mut reader = self.source_reader(g, c, options.raw, false)?;
3353        let (start, count) = self.resolve_window_via(g, c, window, &mut reader)?;
3354        self.values_f64_window(g, c, start, count, options.raw, &mut reader)
3355    }
3356
3357    /// Windowed [`values`](Self::values) over a URL: deferred conversions
3358    /// (the channel's, unless `raw`, and the time axis a time window
3359    /// searches) are fetched first through a small read-ahead cache, the
3360    /// window is located in [`batched_reads_seeded`](Self::batched_reads_seeded)
3361    /// rounds, and its records are then fetched as one round of concurrent
3362    /// requests — or, above `batch_limit` bytes, streamed one data section at
3363    /// a time.
3364    #[cfg(feature = "http")]
3365    fn values_window_url(
3366        &self,
3367        url: &str,
3368        g: usize,
3369        c: usize,
3370        window: Window,
3371        raw: bool,
3372        batch_limit: u64,
3373    ) -> Result<Vec<f64>, MdfError> {
3374        let mut cached = CachingRangeReader::with_chunk_size(self.http_source(url)?, 64 * 1024);
3375        if self.file_size > 0 {
3376            cached.set_known_size(self.file_size);
3377        }
3378        let mut conversions = Vec::with_capacity(2);
3379        if !raw {
3380            conversions.push((g, c));
3381        }
3382        if matches!(window, Window::Time(..)) {
3383            conversions.extend(self.time_axis_location(g, c));
3384        }
3385        let mut primed = std::collections::HashSet::new();
3386        for (tg, tc) in conversions {
3387            let channel = &self.channel_groups[tg].channels[tc];
3388            if channel.conversion.is_none() && channel.conversion_addr != 0 && primed.insert(channel.conversion_addr) {
3389                self.resolve_channel_conversion(tg, tc, &mut cached)?;
3390            }
3391        }
3392        let (mut http, fetched) = cached.into_parts();
3393        let mut store = FragmentStore::from_pairs(fetched)?;
3394        let (start, count) = self.batched_reads_seeded(&mut http, &mut store, |r| self.resolve_window(g, c, window, r))?;
3395
3396        let group = &self.channel_groups[g];
3397        // Only sizes the read: a byte-less group (a virtual master) fetches
3398        // nothing, as in `window_read_bytes`.
3399        let record = Self::checked_record_size(group).unwrap_or(0) as u64;
3400        let vlsd: u64 = group.channels[c].vlsd_data_blocks.iter().map(|b| b.size).sum();
3401        if count.saturating_mul(record).saturating_add(vlsd) > batch_limit {
3402            let mut reader = ChunkedUrlReader { http, store };
3403            return self.values_f64_window(g, c, start, count, raw, &mut reader);
3404        }
3405        self.batched_reads_seeded(&mut http, &mut store, |r| self.values_f64_window(g, c, start, count, raw, r))
3406    }
3407
3408    /// First and last master (time) value of the group holding `name`, or
3409    /// `None` for an empty group. Reads just two records. Errors if the group
3410    /// has no master channel.
3411    pub fn time_range(&self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
3412        let (g, c) = self.locate_checked(name, group)?;
3413        // Over a URL only the master is read (in batched rounds), so skip
3414        // `source_reader`, which would also fetch channel `c`'s conversion.
3415        #[cfg(feature = "http")]
3416        if let Source::Url(url) = self.require_source()? {
3417            let mut http = self.http_source(url)?;
3418            return self.batched_reads(&mut http, |r| self.time_range_at(g, c, r));
3419        }
3420        // Only a file source is left here; `raw` would only matter for a URL.
3421        let mut reader = self.source_reader(g, c, false, true)?;
3422        self.time_range_at(g, c, &mut reader)
3423    }
3424
3425    /// [`resolve_window`](Self::resolve_window) over a [`SourceReader`]: a
3426    /// time window over a URL is searched in batched rounds (see
3427    /// [`batched_reads`](Self::batched_reads)) instead of one blocking
3428    /// request per probe.
3429    fn resolve_window_via(
3430        &self,
3431        g: usize,
3432        c: usize,
3433        window: Window,
3434        reader: &mut SourceReader,
3435    ) -> Result<(u64, u64), MdfError> {
3436        match (window, reader) {
3437            #[cfg(feature = "http")]
3438            (Window::Time(..), SourceReader::Url(cached)) => {
3439                self.batched_reads(cached.inner_mut(), |r| self.resolve_window(g, c, window, r))
3440            }
3441            (_, reader) => self.resolve_window(g, c, window, reader),
3442        }
3443    }
3444
3445    /// Run `op` against the bytes fetched so far, recording every range it
3446    /// could not read; fetch all of them **concurrently**, and run it again
3447    /// until it needs nothing more — the native twin of the wasm gap loop
3448    /// (`js/src/mdf-index.ts`). A time-window search then costs
3449    /// ~`log16(records)` rounds of parallel requests instead of one blocking
3450    /// round-trip per probed record (and per data-block header).
3451    #[cfg(feature = "http")]
3452    fn batched_reads<T>(
3453        &self,
3454        http: &mut HttpRangeReader,
3455        op: impl FnMut(&mut RecordingRangeReader<'_>) -> Result<T, MdfError>,
3456    ) -> Result<T, MdfError> {
3457        self.batched_reads_seeded(http, &mut FragmentStore::new(), op)
3458    }
3459
3460    /// [`batched_reads`](Self::batched_reads) starting from bytes already
3461    /// fetched (`store`). Large gaps are split into
3462    /// [`PARALLEL_CHUNK_BYTES`] pieces so one big signal is also fetched over
3463    /// several connections at once.
3464    #[cfg(feature = "http")]
3465    fn batched_reads_seeded<T>(
3466        &self,
3467        http: &mut HttpRangeReader,
3468        store: &mut FragmentStore,
3469        mut op: impl FnMut(&mut RecordingRangeReader<'_>) -> Result<T, MdfError>,
3470    ) -> Result<T, MdfError> {
3471        for _ in 0..MAX_BATCH_ROUNDS {
3472            let mut recorder = RecordingRangeReader { store: &*store, misses: Vec::new(), whole_request: true };
3473            let result = op(&mut recorder);
3474            let misses = std::mem::take(&mut recorder.misses);
3475            if misses.is_empty() {
3476                return result;
3477            }
3478            let spans = split_spans(merge_ranges_bridging(misses, BATCH_BRIDGE_BYTES), PARALLEL_CHUNK_BYTES);
3479            let fetched = http.read_ranges_parallel(&spans)?;
3480            for ((offset, _), bytes) in spans.iter().zip(fetched) {
3481                store.push(*offset, bytes)?;
3482            }
3483        }
3484        Err(MdfError::BlockSerializationError(
3485            "batched read did not converge; the index or source may be inconsistent".to_string(),
3486        ))
3487    }
3488
3489    /// The conversion `read` / `values` apply to channel `name`, fully
3490    /// resolved, or `None` when the channel has none.
3491    ///
3492    /// Indexes built over the network record only a conversion's location;
3493    /// it is then fetched through the attached source on demand.
3494    pub fn conversion(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionInfo>, MdfError> {
3495        Ok(self.conversion_block(name, group)?.as_ref().map(ConversionInfo::from))
3496    }
3497
3498    /// Locate every name (in the group(s) named `group`, when given), failing
3499    /// with `ChannelNotFound` on the first unknown one.
3500    pub(crate) fn locate_all<S: AsRef<str>>(&self, names: &[S], group: Option<&str>) -> Result<Vec<(usize, usize)>, MdfError> {
3501        names.iter().map(|name| self.locate_checked(name.as_ref(), group)).collect()
3502    }
3503
3504    /// A [`Signal`] for channel `(g, c)` from its decoded parts.
3505    fn make_signal(&self, g: usize, c: usize, timestamps: Vec<f64>, values: Vec<Option<DecodedValue>>) -> Signal {
3506        let channel = &self.channel_groups[g].channels[c];
3507        Signal { name: channel.name.clone().unwrap_or_default(), unit: channel.unit.clone(), timestamps, values }
3508    }
3509
3510    /// `read_many` of whole channels from an in-memory file (a mapped file
3511    /// source): the same decoding as [`read`](Self::read), each time axis once.
3512    #[cfg(not(target_arch = "wasm32"))]
3513    fn read_many_from_slice(&self, targets: &[(usize, usize)], raw: bool, data: &[u8]) -> Result<Vec<Signal>, MdfError> {
3514        let mut axes: HashMap<(usize, usize), Vec<f64>> = HashMap::new();
3515        let mut out = Vec::with_capacity(targets.len());
3516        for &(g, c) in targets {
3517            let values = self.read_channel_values_from_slice(g, c, raw, data)?;
3518            let timestamps = match self.master_location(g, c) {
3519                Some(m) => match axes.get(&m) {
3520                    Some(axis) => axis.clone(),
3521                    None => {
3522                        let axis = self.read_channel_values_from_slice_as_f64(m.0, m.1, false, data)?;
3523                        axes.insert(m, axis.clone());
3524                        axis
3525                    }
3526                },
3527                None => Vec::new(),
3528            };
3529            out.push(self.make_signal(g, c, timestamps, values));
3530        }
3531        Ok(out)
3532    }
3533
3534    /// `read_many` over any byte-range reader — the shared core of the URL,
3535    /// wasm-fragment and [`MdfReader`] paths.
3536    ///
3537    /// With a probing reader
3538    /// ([`RecordingRangeReader`](crate::fragments::RecordingRangeReader))
3539    /// every channel is attempted even after one fails, so the gaps of the
3540    /// whole batch are recorded in one pass, and the first error is
3541    /// returned; any other reader stops at the first error. Within the call, a window is resolved once per time axis and
3542    /// each time axis (or its window) is decoded once.
3543    pub(crate) fn read_many_at<R: ByteRangeReader<Error = MdfError>>(
3544        &self,
3545        targets: &[(usize, usize)],
3546        window: Window,
3547        raw: bool,
3548        reader: &mut R,
3549    ) -> Result<Vec<Signal>, MdfError> {
3550        let mut windows = WindowCache::new();
3551        let mut axes = AxisCache::new();
3552        let mut out = Vec::with_capacity(targets.len());
3553        let mut first_error = None;
3554        for &(g, c) in targets {
3555            match self.read_one_at(g, c, window, raw, reader, &mut windows, &mut axes) {
3556                Ok(signal) => out.push(signal),
3557                // Only a probing reader gains from going on (it records the
3558                // remaining channels' gaps); any other reader stops here, as a
3559                // loop of `read` would.
3560                Err(e) if reader.is_probing() => {
3561                    first_error.get_or_insert(e);
3562                }
3563                Err(e) => return Err(e),
3564            }
3565        }
3566        match first_error {
3567            Some(e) => Err(e),
3568            None => Ok(out),
3569        }
3570    }
3571
3572    /// One channel of [`read_many_at`](Self::read_many_at): the same reads
3573    /// as [`read`](Self::read) (`read_signal` / [`read_signal_window`]), with
3574    /// resolved windows and time axes shared through the two caches.
3575    #[allow(clippy::too_many_arguments)]
3576    fn read_one_at<R: ByteRangeReader<Error = MdfError>>(
3577        &self,
3578        g: usize,
3579        c: usize,
3580        window: Window,
3581        raw: bool,
3582        reader: &mut R,
3583        windows: &mut WindowCache,
3584        axes: &mut AxisCache,
3585    ) -> Result<Signal, MdfError> {
3586        let master = self.master_location(g, c);
3587        if window == Window::All {
3588            let values = self.read_channel_values(g, c, raw, reader);
3589            // Read the time axis even when the values failed, so a probing
3590            // reader records both gaps in one pass.
3591            let timestamps = match master {
3592                Some((mg, m)) => Self::cached_axis(axes, (mg, m, 0, u64::MAX), || {
3593                    self.read_channel_values_as_f64(mg, m, false, reader)
3594                }),
3595                None => Ok(Vec::new()),
3596            };
3597            // The channel's own error first, as `read` reports it.
3598            let values = values?;
3599            return Ok(self.make_signal(g, c, timestamps?, values));
3600        }
3601        let (start, count) = self.cached_window(g, c, window, reader, windows)?;
3602        let values = self.read_channel_values_window(g, c, start, count, raw, reader);
3603        let timestamps = match master {
3604            Some((mg, m)) => Self::cached_axis(axes, (mg, m, start, count), || {
3605                self.values_f64_window(mg, m, start, count, false, reader)
3606            }),
3607            None => Ok(Vec::new()),
3608        };
3609        let values = values?;
3610        Ok(self.make_signal(g, c, timestamps?, values))
3611    }
3612
3613    /// [`resolve_window`](Self::resolve_window) through `cache`: a time window
3614    /// depends on the time axis searched, a record window only on the
3615    /// group's record count.
3616    fn cached_window<R: ByteRangeReader<Error = MdfError>>(
3617        &self,
3618        g: usize,
3619        c: usize,
3620        window: Window,
3621        reader: &mut R,
3622        cache: &mut WindowCache,
3623    ) -> Result<(u64, u64), MdfError> {
3624        let axis = match window {
3625            Window::Time(..) => self.time_axis_location(g, c),
3626            _ => None,
3627        };
3628        let key = (axis, self.channel_groups[g].record_count);
3629        if let Some(&resolved) = cache.get(&key) {
3630            return Ok(resolved);
3631        }
3632        let resolved = self.resolve_window(g, c, window, reader)?;
3633        cache.insert(key, resolved);
3634        Ok(resolved)
3635    }
3636
3637    fn cached_axis(
3638        axes: &mut AxisCache,
3639        key: (usize, usize, u64, u64),
3640        decode: impl FnOnce() -> Result<Vec<f64>, MdfError>,
3641    ) -> Result<Vec<f64>, MdfError> {
3642        if let Some(axis) = axes.get(&key) {
3643            return Ok(axis.clone());
3644        }
3645        let axis = decode()?;
3646        axes.insert(key, axis.clone());
3647        Ok(axis)
3648    }
3649
3650    /// `read_many` over a URL: deferred conversions are fetched first through
3651    /// a small read-ahead cache (a `##CC` block and the blocks it references
3652    /// usually sit together, so this costs one request instead of one round
3653    /// per chain level), then every data range of the batch — channels and
3654    /// time axes — is fetched concurrently in [`batched_reads_seeded`]
3655    /// rounds (one round for whole channels; a few more to search a time
3656    /// window).
3657    ///
3658    /// [`batched_reads_seeded`]: Self::batched_reads_seeded
3659    #[cfg(feature = "http")]
3660    fn read_many_url(
3661        &self,
3662        url: &str,
3663        targets: &[(usize, usize)],
3664        window: Window,
3665        raw: bool,
3666    ) -> Result<Vec<Signal>, MdfError> {
3667        self.read_many_url_limited(url, targets, window, raw, BATCH_MEMORY_LIMIT)
3668    }
3669
3670    /// [`read_many_url`](Self::read_many_url) with the size above which
3671    /// whole channels are streamed instead of fetched as one batch.
3672    #[cfg(feature = "http")]
3673    fn read_many_url_limited(
3674        &self,
3675        url: &str,
3676        targets: &[(usize, usize)],
3677        window: Window,
3678        raw: bool,
3679        batch_limit: u64,
3680    ) -> Result<Vec<Signal>, MdfError> {
3681        let mut cached = CachingRangeReader::with_chunk_size(self.http_source(url)?, 64 * 1024);
3682        if self.file_size > 0 {
3683            cached.set_known_size(self.file_size);
3684        }
3685        let mut primed = std::collections::HashSet::new();
3686        for &(g, c) in targets {
3687            let mut conversions = Vec::with_capacity(3);
3688            if !raw {
3689                conversions.push((g, c));
3690            }
3691            conversions.extend(self.master_location(g, c));
3692            if matches!(window, Window::Time(..)) {
3693                conversions.extend(self.time_axis_location(g, c));
3694            }
3695            for (tg, tc) in conversions {
3696                let channel = &self.channel_groups[tg].channels[tc];
3697                if channel.conversion.is_none() && channel.conversion_addr != 0 && primed.insert(channel.conversion_addr) {
3698                    self.resolve_channel_conversion(tg, tc, &mut cached)?;
3699                }
3700            }
3701        }
3702        let (mut http, fetched) = cached.into_parts();
3703        let mut store = FragmentStore::from_pairs(fetched)?;
3704        let bytes = if window == Window::All {
3705            self.whole_read_bytes(targets)
3706        } else {
3707            // Locate every window first (a few rounds of single-record
3708            // probes), to know how much the read itself will fetch.
3709            // A failure here is left to the read below — the streaming
3710            // path, a plain sequential read that keeps memory bounded and
3711            // reports the channels' errors in the same order as a loop of
3712            // `read`.
3713            match self.batched_reads_seeded(&mut http, &mut store, |r| self.resolve_windows(targets, window, r)) {
3714                Ok(resolved) => self.window_read_bytes(targets, &resolved),
3715                Err(_) => u64::MAX,
3716            }
3717        };
3718        if bytes > batch_limit {
3719            // Too much to hold at once: stream channel by channel (one
3720            // section in memory at a time), each large section still fetched
3721            // as concurrent chunks; time axes are still read once, and the
3722            // window probes are served from the bytes already fetched.
3723            let mut reader = ChunkedUrlReader { http, store };
3724            return self.read_many_at(targets, window, raw, &mut reader);
3725        }
3726        self.batched_reads_seeded(&mut http, &mut store, |r| self.read_many_at(targets, window, raw, r))
3727    }
3728
3729    /// The record window `(start, count)` of every target, resolved as
3730    /// [`read_many_at`](Self::read_many_at) does (once per time axis). Every
3731    /// target is attempted, so a probing reader records all probes of a round.
3732    #[cfg(feature = "http")]
3733    fn resolve_windows<R: ByteRangeReader<Error = MdfError>>(
3734        &self,
3735        targets: &[(usize, usize)],
3736        window: Window,
3737        reader: &mut R,
3738    ) -> Result<Vec<(u64, u64)>, MdfError> {
3739        let mut cache = WindowCache::new();
3740        let mut out = Vec::with_capacity(targets.len());
3741        let mut first_error = None;
3742        for &(g, c) in targets {
3743            match self.cached_window(g, c, window, reader, &mut cache) {
3744                Ok(resolved) => out.push(resolved),
3745                Err(e) => {
3746                    first_error.get_or_insert(e);
3747                }
3748            }
3749        }
3750        match first_error {
3751            Some(e) => Err(e),
3752            None => Ok(out),
3753        }
3754    }
3755
3756    /// Upper bound of the bytes a windowed `read_many` fetches once its
3757    /// windows are resolved: the selected records of every group involved
3758    /// (each group once, at its widest window) plus the `##SD` streams of
3759    /// VLSD channels.
3760    #[cfg(feature = "http")]
3761    fn window_read_bytes(&self, targets: &[(usize, usize)], resolved: &[(u64, u64)]) -> u64 {
3762        let mut records: std::collections::BTreeMap<usize, u64> = std::collections::BTreeMap::new();
3763        let mut total = 0u64;
3764        for (&(g, c), &(_, count)) in targets.iter().zip(resolved) {
3765            for group in std::iter::once(g).chain(self.master_location(g, c).map(|(mg, _)| mg)) {
3766                let widest = records.entry(group).or_default();
3767                *widest = (*widest).max(count);
3768            }
3769            let channel = &self.channel_groups[g].channels[c];
3770            total = total.saturating_add(channel.vlsd_data_blocks.iter().map(|b| b.size).sum());
3771        }
3772        records.into_iter().fold(total, |sum, (g, count)| {
3773            let record = Self::checked_record_size(&self.channel_groups[g]).unwrap_or(0) as u64;
3774            sum.saturating_add(count.saturating_mul(record))
3775        })
3776    }
3777
3778    /// Bytes a whole-channel `read_many` of `targets` fetches: every data
3779    /// block of their groups and of their time groups (each group once),
3780    /// plus the `##SD` streams of VLSD channels.
3781    #[cfg(feature = "http")]
3782    fn whole_read_bytes(&self, targets: &[(usize, usize)]) -> u64 {
3783        let mut groups = std::collections::BTreeSet::new();
3784        let mut total = 0u64;
3785        for &(g, c) in targets {
3786            groups.insert(g);
3787            if let Some((mg, _)) = self.master_location(g, c) {
3788                groups.insert(mg);
3789            }
3790            let channel = &self.channel_groups[g].channels[c];
3791            total = total.saturating_add(channel.vlsd_data_blocks.iter().map(|b| b.size).sum());
3792        }
3793        groups
3794            .iter()
3795            .flat_map(|&g| self.channel_groups[g].data_blocks.iter())
3796            .fold(total, |sum, b| sum.saturating_add(b.size))
3797    }
3798
3799    /// Records `[start, start + count)` a window selects in the group of `(g, c)`.
3800    pub(crate) fn resolve_window<R: ByteRangeReader<Error = MdfError>>(
3801        &self,
3802        g: usize,
3803        c: usize,
3804        window: Window,
3805        reader: &mut R,
3806    ) -> Result<(u64, u64), MdfError> {
3807        let total = self.channel_groups[g].record_count;
3808        match window {
3809            Window::All => Ok((0, total)),
3810            Window::Records(start, count) => resolve_records(start, count, total),
3811            Window::Time(t_start, t_end) => self.record_window_for_time(g, c, t_start, t_end, reader),
3812        }
3813    }
3814
3815    /// `f64` values of records `[start, start + count)` of `(g, c)`.
3816    pub(crate) fn values_f64_window<R: ByteRangeReader<Error = MdfError>>(
3817        &self,
3818        g: usize,
3819        c: usize,
3820        start: u64,
3821        count: u64,
3822        raw: bool,
3823        reader: &mut R,
3824    ) -> Result<Vec<f64>, MdfError> {
3825        // Straight to f64: the same values as `read_channel_values_window`
3826        // mapped through `decoded_opt_to_f64`, without the `DecodedValue`s.
3827        let (group, channel) = self.group_and_channel(g, c)?;
3828        Self::check_window(group, start, count)?;
3829        let conversion = Self::read_conversion(channel, reader, raw)?;
3830        self.window_values_f64(group, channel, conversion.as_deref(), start, count, reader)
3831    }
3832
3833    /// First and last value of the time axis of `(g, c)` (two single-record reads).
3834    pub(crate) fn time_range_at<R: ByteRangeReader<Error = MdfError>>(
3835        &self,
3836        g: usize,
3837        c: usize,
3838        reader: &mut R,
3839    ) -> Result<Option<TimeRange>, MdfError> {
3840        let total = self.channel_groups[g].record_count;
3841        let Some((mg, m)) = self.time_axis_location(g, c) else {
3842            if total == 0 {
3843                return Ok(None);
3844            }
3845            let name = self.channel_groups[g].channels[c].name.clone().unwrap_or_default();
3846            return Err(MdfError::InvalidArgument(format!(
3847                "channel '{name}' has no master (time) channel"
3848            )));
3849        };
3850        let n = total.min(self.channel_groups[mg].record_count);
3851        if n == 0 {
3852            return Ok(None);
3853        }
3854        let first = self.values_f64_window(mg, m, 0, 1, false, reader);
3855        // Attempt the second read even when the first failed, so a probing
3856        // reader records both gaps in one pass.
3857        let last = self.values_f64_window(mg, m, n - 1, 1, false, reader)?;
3858        Ok(Some(TimeRange { start: first?[0], end: last[0] }))
3859    }
3860
3861    /// Memory-map a file source, naming it in the error when it cannot be
3862    /// opened and refusing it when its size differs from the indexed file.
3863    #[cfg(not(target_arch = "wasm32"))]
3864    fn map_source_file(&self, path: &str) -> Result<memmap2::Mmap, MdfError> {
3865        if is_http_url(path) {
3866            #[cfg(not(feature = "http"))]
3867            return Err(MdfError::InvalidArgument(format!(
3868                "'{path}' is a URL, but mf4-rs was built without the `http` feature"
3869            )));
3870            #[cfg(feature = "http")]
3871            return Err(MdfError::InvalidArgument(format!(
3872                "'{path}' is a URL, not a local file: attach URLs with `set_source` or build the \
3873                 index with `from_url`"
3874            )));
3875        }
3876        if let Some(scheme) = url_scheme(path) {
3877            return Err(MdfError::InvalidArgument(format!(
3878                "unsupported source '{path}': {scheme}:// URLs cannot be read directly — use a \
3879                 local file path or an http(s):// URL (e.g. a presigned S3 / GCS / Azure URL)"
3880            )));
3881        }
3882        let file = std::fs::File::open(path).map_err(|e| {
3883            MdfError::IOError(std::io::Error::new(e.kind(), format!("cannot open source '{path}': {e}")))
3884        })?;
3885        let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
3886        check_resource_size(path, self.file_size, mmap.len() as u64)?;
3887        Ok(mmap)
3888    }
3889
3890    /// An HTTP reader for a URL source that checks every response against
3891    /// the indexed file size.
3892    #[cfg(feature = "http")]
3893    fn http_source(&self, url: &str) -> Result<HttpRangeReader, MdfError> {
3894        let mut http = HttpRangeReader::new(url)?;
3895        if self.file_size > 0 {
3896            http.expect_size(self.file_size);
3897        }
3898        Ok(http)
3899    }
3900
3901    /// A byte-range reader over the attached source, with the conversion of
3902    /// `(g, c)` resolved up front for URL sources (unless `raw`).
3903    /// `with_master`: the read decodes the time axis through this reader (a
3904    /// signal), so the master's conversion is primed too. A URL time-window
3905    /// search runs through `batched_reads`, which bypasses this cache.
3906    fn source_reader(&self, g: usize, c: usize, raw: bool, with_master: bool) -> Result<SourceReader, MdfError> {
3907        let _ = (g, c, raw, with_master);
3908        match self.require_source()? {
3909            #[cfg(not(target_arch = "wasm32"))]
3910            Source::File(path) => Ok(SourceReader::File(MmapRangeReader { mmap: self.map_source_file(path)? })),
3911            #[cfg(target_arch = "wasm32")]
3912            Source::File(_) => Err(MdfError::BlockSerializationError(
3913                "file sources are not available on wasm32".to_string(),
3914            )),
3915            #[cfg(feature = "http")]
3916            Source::Url(url) => {
3917                let http = self.http_source(url)?;
3918                Ok(SourceReader::Url(self.url_reader_with_conversion(http, g, c, raw, with_master)?))
3919            }
3920        }
3921    }
3922
3923    /// Decode a channel + its group master from the attached source.
3924    fn read_signal(&self, g: usize, c: usize, raw: bool) -> Result<Signal, MdfError> {
3925        let channel = &self.channel_groups[g].channels[c];
3926        let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
3927
3928        // A file source is mapped once for the values and the time axis.
3929        #[cfg(not(target_arch = "wasm32"))]
3930        #[allow(irrefutable_let_patterns)] // `File` is the only source without `http`
3931        if let Source::File(path) = self.require_source()? {
3932            let mmap = self.map_source_file(path)?;
3933            let values = self.read_channel_values_from_slice(g, c, raw, &mmap)?;
3934            let timestamps = match self.master_location(g, c) {
3935                Some((mg, m)) => self.read_channel_values_from_slice_as_f64(mg, m, false, &mmap)?,
3936                None => Vec::new(),
3937            };
3938            return Ok(Signal { name, unit, timestamps, values });
3939        }
3940
3941        let values = self.read_values_via_source(g, c, raw)?;
3942        let timestamps = match self.master_location(g, c) {
3943            Some((mg, m)) => self.read_values_f64_via_source(mg, m, false)?,
3944            None => Vec::new(),
3945        };
3946
3947        Ok(Signal { name, unit, timestamps, values })
3948    }
3949
3950    /// Wrap `http` for a value read of `(g, c)`: a deferred conversion is
3951    /// fetched first through a small (64 KiB) read-ahead cache — the `##CC`
3952    /// block and the text/conversion blocks it references usually sit next to
3953    /// each other, so this costs one request instead of one per block — then
3954    /// the cache switches to bypass mode so the bulk data is streamed directly
3955    /// (cached conversion bytes are still served from memory).
3956    ///
3957    /// A `raw` read skips the channel's conversion. `with_master` also primes
3958    /// the group master's, for reads that decode the time axis through this
3959    /// reader (windows, signals): otherwise a raw read would resolve it later
3960    /// in bypass mode, one sequential request per block.
3961    #[cfg(feature = "http")]
3962    fn url_reader_with_conversion(
3963        &self,
3964        http: HttpRangeReader,
3965        g: usize,
3966        c: usize,
3967        raw: bool,
3968        with_master: bool,
3969    ) -> Result<CachingRangeReader<HttpRangeReader>, MdfError> {
3970        let mut cached = CachingRangeReader::with_chunk_size(http, 64 * 1024);
3971        if self.file_size > 0 {
3972            cached.set_known_size(self.file_size);
3973        }
3974        let mut targets = Vec::with_capacity(2);
3975        if !raw {
3976            targets.push((g, c));
3977        }
3978        if with_master {
3979            targets.extend(self.master_location(g, c));
3980        }
3981        for (tg, tc) in targets {
3982            let channel = &self.channel_groups[tg].channels[tc];
3983            if channel.conversion.is_none() && channel.conversion_addr != 0 {
3984                self.resolve_channel_conversion(tg, tc, &mut cached)?;
3985            }
3986        }
3987        cached.set_bypass(true);
3988        Ok(cached)
3989    }
3990
3991    /// Resolve the attached [`Source`], erroring with a helpful message if none.
3992    fn require_source(&self) -> Result<&Source, MdfError> {
3993        let source = self.source.as_ref().ok_or_else(|| {
3994            MdfError::BlockSerializationError(
3995                "no data source attached to index; build with from_file/from_url or call set_source".to_string(),
3996            )
3997        })?;
3998        #[cfg(not(feature = "http"))]
3999        {
4000            let Source::File(path) = source;
4001            if is_http_url(path) {
4002                return Err(MdfError::InvalidArgument(format!(
4003                    "'{path}' is a URL, but mf4-rs was built without the `http` feature"
4004                )));
4005            }
4006        }
4007        Ok(source)
4008    }
4009
4010    /// Read one channel's decoded values lazily through the attached source.
4011    pub(crate) fn read_values_via_source(
4012        &self,
4013        g: usize,
4014        c: usize,
4015        raw: bool,
4016    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
4017        #[cfg(target_arch = "wasm32")]
4018        let _ = (g, c, raw);
4019        match self.require_source()? {
4020            #[cfg(not(target_arch = "wasm32"))]
4021            Source::File(path) => {
4022                let mmap = self.map_source_file(path)?;
4023                self.read_channel_values_from_slice(g, c, raw, &mmap)
4024            }
4025            #[cfg(target_arch = "wasm32")]
4026            Source::File(_) => Err(MdfError::BlockSerializationError(
4027                "file sources are not available on wasm32".to_string(),
4028            )),
4029            #[cfg(feature = "http")]
4030            Source::Url(url) => {
4031                let http = self.http_source(url)?;
4032                let mut cached = self.url_reader_with_conversion(http, g, c, raw, false)?;
4033                self.read_channel_values(g, c, raw, &mut cached)
4034            }
4035        }
4036    }
4037
4038    /// Resolve a channel's conversion, fetching it through the attached source
4039    /// if it was not resolved at index-build time (the remote / range-reader
4040    /// path records only its location — see [`IndexedChannel::conversion_addr`]).
4041    ///
4042    /// Returns `None` when the channel has no conversion. Errors if resolution
4043    /// needs the source (a deferred conversion) but none is attached — attach
4044    /// one with [`set_source`](Self::set_source).
4045    ///
4046    /// This returns the raw [`ConversionBlock`]; [`conversion`](Self::conversion)
4047    /// is the contract method returning a plain [`ConversionInfo`].
4048    pub fn conversion_block(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionBlock>, MdfError> {
4049        let (g, c) = self.locate_checked(name, group)?;
4050        let channel = &self.channel_groups[g].channels[c];
4051        if let Some(conv) = &channel.conversion {
4052            return Ok(Some(conv.clone()));
4053        }
4054        if channel.conversion_addr == 0 {
4055            return Ok(None);
4056        }
4057        match self.require_source()? {
4058            #[cfg(not(target_arch = "wasm32"))]
4059            Source::File(path) => {
4060                let mmap = self.map_source_file(path)?;
4061                let mut slice_reader = BorrowedSliceReader { data: &mmap };
4062                Ok(Self::resolve_conversion(channel, &mut slice_reader)?.map(Cow::into_owned))
4063            }
4064            #[cfg(target_arch = "wasm32")]
4065            Source::File(_) => Err(MdfError::BlockSerializationError(
4066                "file sources are not available on wasm32".to_string(),
4067            )),
4068            #[cfg(feature = "http")]
4069            Source::Url(url) => {
4070                let http = self.http_source(url)?;
4071                let mut cached = CachingRangeReader::new(http);
4072                Ok(Self::resolve_conversion(channel, &mut cached)?.map(Cow::into_owned))
4073            }
4074        }
4075    }
4076
4077    /// Read one channel's values as `f64` lazily through the attached source.
4078    pub(crate) fn read_values_f64_via_source(
4079        &self,
4080        g: usize,
4081        c: usize,
4082        raw: bool,
4083    ) -> Result<Vec<f64>, MdfError> {
4084        #[cfg(target_arch = "wasm32")]
4085        let _ = (g, c, raw);
4086        match self.require_source()? {
4087            #[cfg(not(target_arch = "wasm32"))]
4088            Source::File(path) => {
4089                let mmap = self.map_source_file(path)?;
4090                self.read_channel_values_from_slice_as_f64(g, c, raw, &mmap)
4091            }
4092            #[cfg(target_arch = "wasm32")]
4093            Source::File(_) => Err(MdfError::BlockSerializationError(
4094                "file sources are not available on wasm32".to_string(),
4095            )),
4096            #[cfg(feature = "http")]
4097            Source::Url(url) => {
4098                let http = self.http_source(url)?;
4099                let mut cached = self.url_reader_with_conversion(http, g, c, raw, false)?;
4100                self.read_channel_values_as_f64(g, c, raw, &mut cached)
4101            }
4102        }
4103    }
4104
4105    /// Get the exact byte ranges needed to read all data for a specific channel
4106    /// 
4107    /// Returns a vector of (file_offset, length) tuples representing the byte ranges
4108    /// that need to be read from the file to get all data for the specified channel.
4109    /// 
4110    /// # Arguments
4111    /// * `group_index` - Index of the channel group
4112    /// * `channel_index` - Index of the channel within the group
4113    /// 
4114    /// # Returns
4115    /// * `Ok(Vec<(u64, u64)>)` - Vector of (offset, length) byte ranges
4116    /// * `Err(MdfError)` - If indices are invalid or channel type not supported
4117    pub(crate) fn get_channel_byte_ranges(
4118        &self,
4119        group_index: usize,
4120        channel_index: usize,
4121    ) -> Result<Vec<(u64, u64)>, MdfError> {
4122        let group = self.channel_groups.get(group_index)
4123            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4124        
4125        let channel = group.channels.get(channel_index)
4126            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4127
4128        // VLSD channels not supported for byte range calculation
4129        Self::ensure_not_vlsd(channel)?;
4130
4131        // For regular channels, calculate byte ranges from data blocks
4132        self.calculate_regular_channel_byte_ranges(group, channel)
4133    }
4134
4135    /// Get the exact byte ranges for a specific record range of a channel
4136    /// 
4137    /// This is useful when you only want to read a subset of records rather than all data.
4138    /// 
4139    /// # Arguments
4140    /// * `group_index` - Index of the channel group
4141    /// * `channel_index` - Index of the channel within the group
4142    /// * `start_record` - Starting record index (0-based)
4143    /// * `record_count` - Number of records to read
4144    /// 
4145    /// # Returns
4146    /// * `Ok(Vec<(u64, u64)>)` - Vector of (offset, length) byte ranges
4147    /// * `Err(MdfError)` - If indices are invalid, range is out of bounds, or channel type not supported
4148    pub(crate) fn get_channel_byte_ranges_for_records(
4149        &self,
4150        group_index: usize,
4151        channel_index: usize,
4152        start_record: u64,
4153        record_count: u64,
4154    ) -> Result<Vec<(u64, u64)>, MdfError> {
4155        let group = self.channel_groups.get(group_index)
4156            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4157        
4158        let channel = group.channels.get(channel_index)
4159            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4160
4161        // Validate record range with checked arithmetic (forged inputs must
4162        // error, not wrap), and without underflowing when record_count == 0.
4163        let end_record = start_record.checked_add(record_count).ok_or_else(|| {
4164            MdfError::BlockSerializationError(format!(
4165                "Record range overflow: start {} + count {}",
4166                start_record, record_count
4167            ))
4168        })?;
4169        if end_record > group.record_count {
4170            return Err(MdfError::BlockSerializationError(
4171                format!("Record range starting at {} for {} records exceeds total records {}",
4172                    start_record, record_count, group.record_count)
4173            ));
4174        }
4175
4176        // VLSD channels not supported for byte range calculation
4177        Self::ensure_not_vlsd(channel)?;
4178
4179        self.calculate_channel_byte_ranges_for_records(group, channel, start_record, record_count)
4180    }
4181
4182    /// Calculate byte ranges for a regular (non-VLSD) channel for all records
4183    fn calculate_regular_channel_byte_ranges(
4184        &self,
4185        group: &IndexedChannelGroup,
4186        channel: &IndexedChannel,
4187    ) -> Result<Vec<(u64, u64)>, MdfError> {
4188        self.calculate_channel_byte_ranges_for_records(group, channel, 0, group.record_count)
4189    }
4190
4191    /// Calculate byte ranges for a regular channel for a specific record range
4192    fn calculate_channel_byte_ranges_for_records(
4193        &self,
4194        group: &IndexedChannelGroup,
4195        channel: &IndexedChannel,
4196        start_record: u64,
4197        record_count: u64,
4198    ) -> Result<Vec<(u64, u64)>, MdfError> {
4199        // Record structure: record_id + data_bytes + invalidation_bytes
4200        let record_size = Self::checked_record_size(group)?;
4201        let channel_offset_in_record = group.record_id_len as usize + channel.byte_offset as usize;
4202        
4203        // Calculate how many bytes this channel needs per record
4204        let channel_bytes_per_record = if matches!(channel.data_type,
4205            DataType::StringLatin1 | DataType::StringUtf8 | DataType::StringUtf16LE | 
4206            DataType::StringUtf16BE | DataType::ByteArray | DataType::MimeSample | DataType::MimeStream)
4207        {
4208            channel.bit_count as usize / 8
4209        } else {
4210            (channel.bit_offset as usize + channel.bit_count as usize).div_ceil(8).max(1)
4211        };
4212
4213        // The data blocks form one byte stream in which record `r`'s field
4214        // occupies `[r·size + offset, r·size + offset + len)`; a record (and
4215        // even the field) may straddle two blocks. Per block, return the span
4216        // from the first to the last field byte of the selected records it
4217        // holds.
4218        let size = record_size as u64;
4219        let (field_offset, field_len) = (channel_offset_in_record as u64, channel_bytes_per_record as u64);
4220        let end_record = start_record + record_count;
4221        let mut byte_ranges = Vec::new();
4222        let mut block_start = 0u64; // stream offset of the block's first data byte
4223
4224        for data_block in &group.data_blocks {
4225            if data_block.is_compressed {
4226                return Err(MdfError::BlockSerializationError(
4227                    "Compressed blocks not supported for byte range calculation".to_string()
4228                ));
4229            }
4230            let block_end = block_start.saturating_add(Self::data_section_size(data_block)?);
4231            if record_count == 0 || field_len == 0 || block_start >= end_record.saturating_mul(size) {
4232                break;
4233            }
4234            // Selected records whose field intersects [block_start, block_end):
4235            // r·size + offset < block_end and r·size + offset + len > block_start.
4236            let first = (block_start + 1).saturating_sub(field_offset + field_len).div_ceil(size);
4237            let first = first.max(start_record);
4238            let last = match block_end.checked_sub(field_offset + 1) {
4239                Some(v) => (v / size).min(end_record - 1),
4240                None => {
4241                    block_start = block_end;
4242                    continue;
4243                }
4244            };
4245            if first <= last {
4246                let lo = (first * size + field_offset).max(block_start);
4247                let hi = (last * size + field_offset + field_len).min(block_end);
4248                if lo < hi {
4249                    byte_ranges.push((data_block.file_offset + 24 + (lo - block_start), hi - lo));
4250                }
4251            }
4252            block_start = block_end;
4253        }
4254
4255        Ok(byte_ranges)
4256    }
4257
4258    /// Byte ranges occupied by a channel across the whole file, by name.
4259    ///
4260    /// Each tuple is `(offset, length)`, accounting for the channel's position
4261    /// in the record layout and any data-block splitting. Resolves the first
4262    /// channel matching `name`. Power-user entry point for issuing HTTP-range
4263    /// or S3 partial reads yourself.
4264    ///
4265    /// Note: each returned range is one *coalesced* span per data-block
4266    /// fragment, running from the first byte of the channel in the fragment's
4267    /// first record to its last byte in the fragment's last record (clipped
4268    /// at the fragment's edges when a record — or the channel's field itself
4269    /// — is split between two fragments). Because records interleave all
4270    /// channels of the group, the span **includes the bytes of the other
4271    /// channels** lying between this channel's samples.
4272    ///
4273    /// Pass `group` to resolve the channel in the group(s) with that name.
4274    /// Refused for VLSD channels (use `read` / `values`).
4275    pub fn byte_ranges(&self, name: &str, group: Option<&str>) -> Result<Vec<(u64, u64)>, MdfError> {
4276        let (g, c) = self.locate_checked(name, group)?;
4277        self.get_channel_byte_ranges(g, c)
4278    }
4279
4280    /// Byte ranges for a record window of a channel, by name.
4281    ///
4282    /// `start_record` is 0-based. Errors if `start_record + record_count`
4283    /// exceeds the records available. Useful for paging through a large
4284    /// channel. See [`MdfIndex::byte_ranges`] for what each returned span
4285    /// covers.
4286    pub fn byte_ranges_for_records(
4287        &self,
4288        name: &str,
4289        start_record: u64,
4290        record_count: u64,
4291        group: Option<&str>,
4292    ) -> Result<Vec<(u64, u64)>, MdfError> {
4293        let (g, c) = self.locate_checked(name, group)?;
4294        self.get_channel_byte_ranges_for_records(g, c, start_record, record_count)
4295    }
4296
4297    /// Fast path: read channel values as `Vec<f64>` using a byte range reader.
4298    ///
4299    /// This avoids boxing `DecodedValue` enums and applies linear conversions inline.
4300    /// For channels without invalidation bytes (the common case), validity checking
4301    /// is skipped entirely. Invalid samples are represented as `f64::NAN`.
4302    pub(crate) fn read_channel_values_as_f64<R: ByteRangeReader<Error = MdfError>>(
4303        &self,
4304        group_index: usize,
4305        channel_index: usize,
4306        raw: bool,
4307        reader: &mut R,
4308    ) -> Result<Vec<f64>, MdfError> {
4309        let group = self.channel_groups.get(group_index)
4310            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4311        let channel = group.channels.get(channel_index)
4312            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4313
4314        let conversion = Self::read_conversion(channel, reader, raw)?;
4315
4316        if channel.is_virtual() {
4317            let vals = self.virtual_values(group, 0, group.record_count, conversion.as_deref())?;
4318            return Ok(Self::vlsd_values_to_f64(vals));
4319        }
4320        if channel.channel_type == 1 {
4321            let vals = self.read_vlsd_channel_values(group, channel, conversion.as_deref(), reader)?;
4322            return Ok(Self::vlsd_values_to_f64(vals));
4323        }
4324
4325        let record_size = Self::checked_record_size(group)?;
4326        let total_records = Self::whole_read_records(group)?;
4327        // Cap the pre-allocation: `total_records` derives from index-supplied
4328        // block sizes, and a forged value must not abort on allocation. The
4329        // vector still grows as needed; real reads fail earlier at the reader.
4330        let mut values = Vec::with_capacity(total_records.min(1 << 24));
4331
4332        let temp_cb = channel.to_decode_only_channel_block();
4333        let linear_coeffs = Self::get_linear_coeffs(conversion.as_deref());
4334        let has_conversion = conversion.is_some();
4335
4336        // Records split between two blocks are reassembled.
4337        let mut records = RecordCarry::new(record_size);
4338        Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
4339            records.feed(block_data, |run| {
4340                Self::decode_records_to_f64(run, record_size, group, channel, conversion.as_deref(), &temp_cb, linear_coeffs, has_conversion, &mut values)
4341            })
4342        })?;
4343
4344        Ok(values)
4345    }
4346
4347    /// Zero-copy fast path: read channel values directly from an `&[u8]` mmap slice.
4348    ///
4349    /// Avoids all per-block heap allocation by slicing directly into the provided
4350    /// memory-mapped region. This is the fastest `DecodedValue` read path when the
4351    /// entire file is already mapped into memory.
4352    #[allow(dead_code)] // used by the Python bindings (pyo3 feature)
4353    pub(crate) fn read_channel_values_from_slice(
4354        &self,
4355        group_index: usize,
4356        channel_index: usize,
4357        raw: bool,
4358        file_data: &[u8],
4359    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
4360        let group = self.channel_groups.get(group_index)
4361            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4362        let channel = group.channels.get(channel_index)
4363            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4364
4365        let mut slice_reader = BorrowedSliceReader { data: file_data };
4366        let conversion = Self::read_conversion(channel, &mut slice_reader, raw)?;
4367
4368        if channel.is_virtual() {
4369            return self.virtual_values(group, 0, group.record_count, conversion.as_deref());
4370        }
4371        if channel.channel_type == 1 {
4372            return self.read_vlsd_channel_values(group, channel, conversion.as_deref(), &mut slice_reader);
4373        }
4374
4375        let record_size = Self::checked_record_size(group)?;
4376        let total_records = Self::whole_read_records(group)?;
4377        // Cap the pre-allocation: `total_records` derives from index-supplied
4378        // block sizes, and a forged value must not abort on allocation. The
4379        // vector still grows as needed; real reads fail earlier at the reader.
4380        let mut values = Vec::with_capacity(total_records.min(1 << 24));
4381        let temp_cb = channel.to_decode_only_channel_block();
4382
4383        // Records split between two blocks are reassembled.
4384        let mut records = RecordCarry::new(record_size);
4385        for data_block in &group.data_blocks {
4386            let block_data = Self::slice_data_block(file_data, data_block)?;
4387            records.feed(block_data, |run| {
4388                Self::decode_records_to_values(run, record_size, group, conversion.as_deref(), &temp_cb, &mut values)
4389            })?;
4390        }
4391
4392        Ok(values)
4393    }
4394
4395    /// Zero-copy fast path: read channel values as `Vec<f64>` directly from an `&[u8]` mmap slice.
4396    ///
4397    /// Combines zero-copy slice access with the f64 fast decode path. No per-block
4398    /// allocation, no `DecodedValue` enum boxing. This is the fastest possible read
4399    /// path. Invalid or undecodable samples are `f64::NAN`.
4400    #[allow(dead_code)] // used by the Python bindings (pyo3 feature)
4401    pub(crate) fn read_channel_values_from_slice_as_f64(
4402        &self,
4403        group_index: usize,
4404        channel_index: usize,
4405        raw: bool,
4406        file_data: &[u8],
4407    ) -> Result<Vec<f64>, MdfError> {
4408        let group = self.channel_groups.get(group_index)
4409            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4410        let channel = group.channels.get(channel_index)
4411            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4412
4413        let mut slice_reader = BorrowedSliceReader { data: file_data };
4414        let conversion = Self::read_conversion(channel, &mut slice_reader, raw)?;
4415
4416        if channel.is_virtual() {
4417            let vals = self.virtual_values(group, 0, group.record_count, conversion.as_deref())?;
4418            return Ok(Self::vlsd_values_to_f64(vals));
4419        }
4420        if channel.channel_type == 1 {
4421            let vals = self.read_vlsd_channel_values(group, channel, conversion.as_deref(), &mut slice_reader)?;
4422            return Ok(Self::vlsd_values_to_f64(vals));
4423        }
4424
4425        let record_size = Self::checked_record_size(group)?;
4426        let total_records = Self::whole_read_records(group)?;
4427        // Cap the pre-allocation: `total_records` derives from index-supplied
4428        // block sizes, and a forged value must not abort on allocation. The
4429        // vector still grows as needed; real reads fail earlier at the reader.
4430        let mut values = Vec::with_capacity(total_records.min(1 << 24));
4431        let temp_cb = channel.to_decode_only_channel_block();
4432        let linear_coeffs = Self::get_linear_coeffs(conversion.as_deref());
4433        let has_conversion = conversion.is_some();
4434
4435        // Records split between two blocks are reassembled.
4436        let mut records = RecordCarry::new(record_size);
4437        for data_block in &group.data_blocks {
4438            let block_data = Self::slice_data_block(file_data, data_block)?;
4439            records.feed(block_data, |run| {
4440                Self::decode_records_to_f64(run, record_size, group, channel, conversion.as_deref(), &temp_cb, linear_coeffs, has_conversion, &mut values)
4441            })?;
4442        }
4443
4444        Ok(values)
4445    }
4446
4447    /// Slice a data block from file_data, skipping the 24-byte block header.
4448    /// Uses checked arithmetic so a forged offset/size errors instead of
4449    /// wrapping or panicking.
4450    #[allow(dead_code)] // used by the Python bindings (pyo3 feature)
4451    fn slice_data_block<'a>(file_data: &'a [u8], data_block: &DataBlockInfo) -> Result<&'a [u8], MdfError> {
4452        Self::data_section_size(data_block)?;
4453        let too_short = |expected: usize| MdfError::TooShortBuffer {
4454            actual: file_data.len(),
4455            expected,
4456            file: file!(),
4457            line: line!(),
4458        };
4459        let data_start = usize::try_from(data_block.file_offset)
4460            .ok()
4461            .and_then(|o| o.checked_add(24))
4462            .ok_or_else(|| too_short(usize::MAX))?;
4463        // The block header's own length wins over the indexed size.
4464        let data_len = Self::verified_data_len(file_data.get(data_start - 24..data_start), data_block)?;
4465        let data_end = usize::try_from(data_len)
4466            .ok()
4467            .and_then(|l| data_start.checked_add(l))
4468            .ok_or_else(|| too_short(usize::MAX))?;
4469        file_data.get(data_start..data_end).ok_or_else(|| too_short(data_end))
4470    }
4471}
4472
4473/// A reader bound to an [`MdfIndex`] and a single byte-range data source.
4474///
4475/// Obtained from [`MdfIndex::open`] / [`MdfIndex::open_file`]. The source is
4476/// supplied once; afterwards channels are read by name. Reads of the same
4477/// channel re-fetch from the underlying source, so cache or memory-map the
4478/// source (e.g. [`MmapRangeReader`], [`CachingRangeReader`]) when reading many
4479/// channels.
4480pub struct MdfReader<'a, R: ByteRangeReader<Error = MdfError>> {
4481    index: &'a MdfIndex,
4482    reader: R,
4483}
4484
4485impl<'a, R: ByteRangeReader<Error = MdfError>> MdfReader<'a, R> {
4486    /// The index this reader was opened against.
4487    pub fn index(&self) -> &MdfIndex {
4488        self.index
4489    }
4490
4491    /// Mutable access to the underlying byte-range reader (e.g. to toggle
4492    /// [`CachingRangeReader::set_bypass`] or inspect request counters).
4493    pub fn reader_mut(&mut self) -> &mut R {
4494        &mut self.reader
4495    }
4496
4497    /// Consume the reader, returning the underlying byte-range source.
4498    pub fn into_inner(self) -> R {
4499        self.reader
4500    }
4501
4502    /// Read a channel as a [`Signal`] — see [`MdfIndex::read`].
4503    pub fn read<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
4504        let default = ReadOptions::default();
4505        let options = options.into().unwrap_or(&default);
4506        let window = options.window()?;
4507        let (g, c) = self.index.locate_checked(name, options.group_name())?;
4508        if window == Window::All {
4509            return self.read_signal(g, c, options.raw);
4510        }
4511        let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
4512        read_signal_window(self.index, g, c, start, count, options.raw, &mut self.reader)
4513    }
4514
4515    /// Read several channels at once — see [`MdfIndex::read_many`].
4516    pub fn read_many<'o, S: AsRef<str>>(
4517        &mut self,
4518        names: &[S],
4519        options: impl Into<Option<&'o ReadOptions>>,
4520    ) -> Result<Vec<Signal>, MdfError> {
4521        let default = ReadOptions::default();
4522        let options = options.into().unwrap_or(&default);
4523        let window = options.window()?;
4524        let targets = self.index.locate_all(names, options.group_name())?;
4525        self.index.read_many_at(&targets, window, options.raw, &mut self.reader)
4526    }
4527
4528    /// Read a numeric channel as plain `f64` values — see [`MdfIndex::values`].
4529    pub fn values<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
4530        let default = ReadOptions::default();
4531        let options = options.into().unwrap_or(&default);
4532        let window = options.window()?;
4533        let (g, c) = self.index.locate_checked(name, options.group_name())?;
4534        if window == Window::All {
4535            return self.index.read_channel_values_as_f64(g, c, options.raw, &mut self.reader);
4536        }
4537        let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
4538        self.index.values_f64_window(g, c, start, count, options.raw, &mut self.reader)
4539    }
4540
4541    /// Rust-only: all samples of a channel as decoded values (no time axis),
4542    /// keeping text and byte values that `values` would turn into `NaN`.
4543    pub fn decoded_values(&mut self, name: &str, group: Option<&str>) -> Result<Vec<Option<DecodedValue>>, MdfError> {
4544        let (g, c) = self.index.locate_checked(name, group)?;
4545        self.index.read_channel_values(g, c, false, &mut self.reader)
4546    }
4547
4548    /// First and last master (time) value of the group holding `name` — see
4549    /// [`MdfIndex::time_range`].
4550    pub fn time_range(&mut self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
4551        let (g, c) = self.index.locate_checked(name, group)?;
4552        self.index.time_range_at(g, c, &mut self.reader)
4553    }
4554
4555    fn read_signal(&mut self, g: usize, c: usize, raw: bool) -> Result<Signal, MdfError> {
4556        let channel = &self.index.channel_groups[g].channels[c];
4557        let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
4558
4559        let values = self.index.read_channel_values(g, c, raw, &mut self.reader)?;
4560        let timestamps = match self.index.master_location(g, c) {
4561            Some((mg, m)) => self.index.read_channel_values_as_f64(mg, m, false, &mut self.reader)?,
4562            None => Vec::new(),
4563        };
4564        Ok(Signal { name, unit, timestamps, values })
4565    }
4566}
4567
4568/// Window read shared by [`MdfReader`] and the wasm fragment driver: records
4569/// `[start, start + count)` of `(g, c)` paired with the same window of its
4570/// time axis.
4571pub(crate) fn read_signal_window<R: ByteRangeReader<Error = MdfError>>(
4572    index: &MdfIndex,
4573    g: usize,
4574    c: usize,
4575    start: u64,
4576    count: u64,
4577    raw: bool,
4578    reader: &mut R,
4579) -> Result<Signal, MdfError> {
4580    let channel = &index.channel_groups[g].channels[c];
4581    let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
4582    let values = index.read_channel_values_window(g, c, start, count, raw, reader);
4583    // Read the master even when the values failed, so a probing reader
4584    // records both gaps in one pass. Like a full read, the master itself
4585    // carries no separate timestamps.
4586    let timestamps = match index.master_location(g, c) {
4587        Some((mg, m)) => index.values_f64_window(mg, m, start, count, false, reader)?,
4588        None => Vec::new(),
4589    };
4590    Ok(Signal { name, unit, timestamps, values: values? })
4591}
4592
4593#[cfg(all(test, feature = "http"))]
4594mod http_header_tests {
4595    use super::{content_range_span, content_range_total};
4596
4597    #[test]
4598    fn parses_content_range() {
4599        assert_eq!(content_range_span(Some("bytes 10-19/100")), Some((10, 19)));
4600        assert_eq!(content_range_span(Some(" bytes 0-0/*")), Some((0, 0)));
4601        assert_eq!(content_range_span(Some("bytes */100")), None);
4602        assert_eq!(content_range_span(None), None);
4603        assert_eq!(content_range_total(Some("bytes 10-19/100")), Some(100));
4604        assert_eq!(content_range_total(Some("bytes */100")), Some(100));
4605        assert_eq!(content_range_total(Some("bytes 0-0/*")), None);
4606    }
4607}
4608
4609#[cfg(all(test, feature = "http"))]
4610mod http_retry_tests {
4611    use super::{ByteRangeReader, HttpRangeReader};
4612    use std::collections::VecDeque;
4613    use std::io::{Read, Write};
4614    use std::sync::atomic::{AtomicU64, Ordering};
4615    use std::sync::{Arc, Mutex};
4616
4617    const OK: &str = "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-3/10\r\nContent-Length: 4\r\n\
4618                      Connection: close\r\n\r\nabcd";
4619    const BUSY: &str = "HTTP/1.1 503 Slow Down\r\nRetry-After: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4620    const MISSING: &str = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4621
4622    /// Serve `script` (one response per connection) and count requests.
4623    fn serve(script: &[&'static str]) -> (String, Arc<AtomicU64>) {
4624        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4625        let url = format!("http://{}/file.mf4", listener.local_addr().unwrap());
4626        let script = Arc::new(Mutex::new(script.iter().copied().collect::<VecDeque<_>>()));
4627        let count = Arc::new(AtomicU64::new(0));
4628        let served = count.clone();
4629        std::thread::spawn(move || {
4630            for stream in listener.incoming() {
4631                let Ok(mut stream) = stream else { return };
4632                let mut head = Vec::new();
4633                let mut byte = [0u8; 1];
4634                while !head.ends_with(b"\r\n\r\n") && stream.read(&mut byte).unwrap_or(0) == 1 {
4635                    head.push(byte[0]);
4636                }
4637                served.fetch_add(1, Ordering::SeqCst);
4638                let response = script.lock().unwrap().pop_front().unwrap_or(MISSING);
4639                let _ = stream.write_all(response.as_bytes());
4640            }
4641        });
4642        (url, count)
4643    }
4644
4645    #[test]
4646    fn transient_failures_are_retried() {
4647        let (url, count) = serve(&[BUSY, BUSY, OK]);
4648        let bytes = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap();
4649        assert_eq!(bytes, b"abcd");
4650        assert_eq!(count.load(Ordering::SeqCst), 3);
4651    }
4652
4653    #[test]
4654    fn retries_are_bounded() {
4655        let (url, count) = serve(&[BUSY, BUSY, BUSY, BUSY, BUSY, OK]);
4656        let error = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap_err().to_string();
4657        assert!(error.contains("503") && error.contains("gave up after 4 attempts"), "{error}");
4658        assert_eq!(count.load(Ordering::SeqCst), 4);
4659    }
4660
4661    #[test]
4662    fn permanent_failures_are_not_retried() {
4663        let (url, count) = serve(&[MISSING, OK]);
4664        let error = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap_err().to_string();
4665        assert!(error.contains("404"), "{error}");
4666        assert_eq!(count.load(Ordering::SeqCst), 1);
4667    }
4668}
4669
4670#[cfg(all(test, feature = "http"))]
4671mod url_read_tests {
4672    use super::{DataBlockInfo, MdfIndex, Window};
4673    use crate::fragments::{FragmentStore, RecordingRangeReader};
4674    use crate::{ColumnData, Mdf, MdfWriter, ReadOptions};
4675    use std::io::{BufRead, BufReader, Write};
4676    use std::sync::Arc;
4677
4678    /// Thread-per-connection server honouring single `Range` requests.
4679    fn serve(bytes: Vec<u8>) -> String {
4680        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4681        let url = format!("http://{}/f.mf4", listener.local_addr().unwrap());
4682        let bytes = Arc::new(bytes);
4683        std::thread::spawn(move || {
4684            for stream in listener.incoming() {
4685                let Ok(stream) = stream else { return };
4686                let bytes = bytes.clone();
4687                std::thread::spawn(move || {
4688                    let mut reader = BufReader::new(stream.try_clone().unwrap());
4689                    let mut stream = stream;
4690                    loop {
4691                        let mut range = None;
4692                        let mut line = String::new();
4693                        loop {
4694                            line.clear();
4695                            if reader.read_line(&mut line).unwrap_or(0) == 0 {
4696                                return;
4697                            }
4698                            if line == "\r\n" {
4699                                break;
4700                            }
4701                            if let Some(v) = line.to_ascii_lowercase().strip_prefix("range: bytes=") {
4702                                let (a, b) = v.trim().split_once('-').unwrap();
4703                                range = Some((a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap()));
4704                            }
4705                        }
4706                        let (a, b) = range.unwrap_or((0, bytes.len() - 1));
4707                        let b = b.min(bytes.len() - 1);
4708                        let head = format!(
4709                            "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {a}-{b}/{}\r\nContent-Length: {}\r\n\r\n",
4710                            bytes.len(),
4711                            b + 1 - a
4712                        );
4713                        // One write per response: a separate head and body
4714                        // write stalls ~40 ms on Nagle + delayed ACK.
4715                        let mut response = head.into_bytes();
4716                        response.extend_from_slice(&bytes[a..=b]);
4717                        if stream.write_all(&response).is_err() {
4718                            return;
4719                        }
4720                    }
4721                });
4722            }
4723        });
4724        url
4725    }
4726
4727    fn build(path: &std::path::Path) {
4728        let mut w = MdfWriter::new(path.to_str().unwrap()).unwrap();
4729        w.init_mdf_file().unwrap();
4730        let g = w.add_channel_group(Some("G")).unwrap();
4731        w.add_time_channel(&g, "t").unwrap();
4732        let a = w.add_float_channel(&g, "A").unwrap();
4733        w.add_float_channel(&g, "B").unwrap();
4734        w.add_linear_conversion(&a, 1.0, 2.0).unwrap();
4735        let n = 300_000;
4736        let t: Vec<f64> = (0..n).map(|i| i as f64 * 1e-3).collect();
4737        let x: Vec<f64> = (0..n).map(|i| (i % 977) as f64).collect();
4738        w.start_data_block(&g).unwrap();
4739        w.write_columns(&g, &[ColumnData::F64(&t), ColumnData::F64(&x), ColumnData::F64(&x)]).unwrap();
4740        w.finish_data_block(&g).unwrap();
4741        w.finalize().unwrap();
4742    }
4743
4744    /// Whole channels and windows over a URL give the same signals batched
4745    /// and streamed (the path taken above the memory limit), on a row-oriented file split
4746    /// into several data blocks and on its column-oriented conversion.
4747    #[test]
4748    fn streamed_and_batched_whole_reads_agree() {
4749        let dir = tempfile::tempdir().unwrap();
4750        let (row, col) = (dir.path().join("row.mf4"), dir.path().join("col.mf4"));
4751        build(&row);
4752        let opts = crate::ColumnOptions { block_size: 256 * 1024, ..Default::default() };
4753        crate::to_column_oriented(&row, &col, &opts).unwrap();
4754        for path in [&row, &col] {
4755            let mdf = Mdf::from_file(path.to_str().unwrap()).unwrap();
4756            let index = MdfIndex::from_file(path.to_str().unwrap()).unwrap();
4757            assert!(index.channel_groups.iter().any(|g| g.data_blocks.len() > 1), "several data blocks");
4758            let url = serve(std::fs::read(path).unwrap());
4759            let names = ["A", "t", "B", "A"];
4760            let targets = index.locate_all(&names, None).unwrap();
4761            let option_sets = [
4762                ReadOptions::new(),
4763                ReadOptions::new().raw(true),
4764                ReadOptions::new().time(Some(12.5), Some(250.0)),
4765                ReadOptions::new().time(Some(100.0), None).raw(true),
4766                ReadOptions::new().records(1000, 150_000),
4767            ];
4768            for options in &option_sets {
4769                let want = mdf.read_many(&names, options).unwrap();
4770                let window = options.window().unwrap();
4771                for limit in [0, u64::MAX] {
4772                    let got = index.read_many_url_limited(&url, &targets, window, options.raw, limit).unwrap();
4773                    for (g, w) in got.iter().zip(&want) {
4774                        assert_eq!((&g.values, &g.timestamps), (&w.values, &w.timestamps), "limit {limit} {options:?}");
4775                    }
4776                    // Windowed `values` takes the same two paths.
4777                    if window != Window::All {
4778                        for (&(g, c), name) in targets.iter().zip(names) {
4779                            let got = index.values_window_url(&url, g, c, window, options.raw, limit).unwrap();
4780                            let want = mdf.values(name, options).unwrap();
4781                            assert_eq!(format!("{got:?}"), format!("{want:?}"), "values limit {limit} {options:?}");
4782                        }
4783                    }
4784                }
4785            }
4786        }
4787    }
4788
4789    /// A probing reader records every missing data section in one pass.
4790    #[test]
4791    fn probing_whole_reads_record_every_section() {
4792        let blocks: Vec<DataBlockInfo> = [0u64, 10_000, 20_000]
4793            .iter()
4794            .map(|&o| DataBlockInfo { file_offset: o, size: 24 + 800, is_compressed: false })
4795            .collect();
4796        let store = FragmentStore::new();
4797        let mut reader = RecordingRangeReader { store: &store, misses: Vec::new(), whole_request: true };
4798        let result = MdfIndex::for_each_data_section(&mut reader, &blocks, |_| Ok(()));
4799        assert!(result.is_err());
4800        assert_eq!(reader.misses, vec![(0, 824), (10_000, 824), (20_000, 824)]);
4801    }
4802}