Skip to main content

mf4_rs/
types.rs

1//! The plain data types of the cross-language API contract.
2//!
3//! Every binding (Rust, Python, TypeScript) exposes these with the same
4//! fields — only the casing differs (`record_count` / `recordCount`). See
5//! `docs/API.md` for the contract and `docs/api-contract.json` for the
6//! machine-readable list the parity tests check.
7
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11
12use crate::blocks::conversion::ConversionBlock;
13use crate::error::MdfError;
14
15/// Metadata of one channel.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase")]
18pub struct ChannelInfo {
19    /// Channel name.
20    pub name: Option<String>,
21    /// Physical unit.
22    pub unit: Option<String>,
23    /// Channel comment (`##TX` text, or the raw `##MD` XML).
24    pub comment: Option<String>,
25    /// Canonical data-type name, e.g. `"FloatLE"` (see
26    /// [`DataType::name`](crate::blocks::common::DataType::name)).
27    pub data_type: String,
28    /// Width of the stored value in bits.
29    pub bit_count: u32,
30    /// The channel is its group's master (time) channel.
31    pub is_master: bool,
32    /// Variable-length (VLSD) channel, e.g. strings.
33    pub is_vlsd: bool,
34    /// The channel carries a conversion (applied by `read` / `values`).
35    pub has_conversion: bool,
36}
37
38/// Metadata of one channel group.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct GroupInfo {
42    /// Group (acquisition) name.
43    pub name: Option<String>,
44    /// Group comment.
45    pub comment: Option<String>,
46    /// Number of records (samples per channel).
47    pub record_count: u64,
48    /// Names of the group's named channels, in file order.
49    pub channel_names: Vec<String>,
50    /// Name of the group's master (time) channel — local, or the remote master
51    /// of an MDF 4.2 column-oriented group.
52    pub master_channel: Option<String>,
53    /// The group's channels, in file order.
54    pub channels: Vec<ChannelInfo>,
55}
56
57impl GroupInfo {
58    /// Find one of this group's channels by name.
59    pub fn channel(&self, name: &str) -> Option<&ChannelInfo> {
60        self.channels.iter().find(|c| c.name.as_deref() == Some(name))
61    }
62}
63
64/// Physical groups that make up the logical group `first` — shared by `Mdf`
65/// and `MdfIndex` so both answer `group(name)` and group-filtered lookups
66/// alike.
67///
68/// `names[i]` is the name of physical group `i`; `time_groups[i]` the group
69/// holding its time axis (itself for a local master, the referenced group for
70/// an MDF 4.2 remote master, `None` when untimed).
71///
72/// A column-oriented file splits one source group into one physical group per
73/// signal, all carrying the source group's name and pointing at a shared time
74/// group — which may carry *another* source group's name when identical time
75/// axes were merged. The logical group is then: that time group (if it has a
76/// different name) followed by every group with `first`'s name that shares
77/// its time axis. An untimed source group becomes untimed one-channel groups
78/// of the same name, which are merged too (`channel_counts[i]` is the number
79/// of channels of group `i`). A row-oriented group (local master, or untimed
80/// with several channels) is just itself.
81pub(crate) fn logical_group_members<S: PartialEq>(
82    names: &[S],
83    time_groups: &[Option<usize>],
84    channel_counts: &[usize],
85    first: usize,
86) -> Vec<usize> {
87    let Some(time_group) = time_groups[first] else {
88        if channel_counts[first] != 1 {
89            return vec![first];
90        }
91        return (0..names.len())
92            .filter(|&h| names[h] == names[first] && time_groups[h].is_none() && channel_counts[h] == 1)
93            .collect();
94    };
95    let mut members = Vec::new();
96    if names[time_group] != names[first] {
97        members.push(time_group);
98    }
99    members.extend(
100        (0..names.len()).filter(|&h| names[h] == names[first] && time_groups[h] == Some(time_group)),
101    );
102    members
103}
104
105/// Merge the [`GroupInfo`] of `first` with those of the other `members` of
106/// its logical group (see [`logical_group_members`]): the channels of all
107/// members, in member order; every other field is `first`'s.
108pub(crate) fn merge_group_infos(first: GroupInfo, members: impl IntoIterator<Item = GroupInfo>) -> GroupInfo {
109    let mut merged = GroupInfo { channel_names: Vec::new(), channels: Vec::new(), ..first };
110    for info in members {
111        merged.channel_names.extend(info.channel_names);
112        merged.channels.extend(info.channels);
113    }
114    merged
115}
116
117/// First and last master (time) value of a channel's group.
118#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
119pub struct TimeRange {
120    pub start: f64,
121    pub end: f64,
122}
123
124/// A channel's conversion (raw → physical value), fully resolved.
125///
126/// `type` is one of `Identity`, `Linear`, `Rational`, `Algebraic`,
127/// `TableLookupInterp`, `TableLookupNoInterp`, `RangeLookup`, `ValueToText`,
128/// `RangeToText`, `TextToValue`, `TextToText`, `BitfieldText`. `values` holds
129/// the block's parameters (`cc_val`): `[offset, factor]` for `Linear`
130/// (`phys = values[0] + values[1] * raw`), the six rational coefficients, or
131/// the table keys. `texts` / `refs` are keyed by the position in the block's
132/// reference list; how they pair with `values` depends on `type` (MDF 4.1
133/// §6.17) — for `ValueToText`, `values[i]` maps to `texts[i]` (or the nested
134/// `refs[i]`) and index `values.len()` is the default.
135#[derive(Debug, Clone, PartialEq, Serialize)]
136#[serde(rename_all = "camelCase")]
137pub struct ConversionInfo {
138    /// Conversion type name.
139    #[serde(rename = "type")]
140    pub conversion_type: String,
141    /// The block's numeric parameters (`cc_val`).
142    pub values: Vec<f64>,
143    /// Decimal places to display.
144    pub precision: u8,
145    /// Raw `cc_flags`.
146    pub flags: u16,
147    /// `[min, max]` physical range, when the block declares one.
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub physical_range: Option<[f64; 2]>,
150    /// Formula of an `Algebraic` conversion (variable `X`).
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub formula: Option<String>,
153    /// Text references, keyed by reference index.
154    #[serde(skip_serializing_if = "BTreeMap::is_empty", serialize_with = "string_keys")]
155    pub texts: BTreeMap<usize, String>,
156    /// Nested conversions, keyed by reference index.
157    #[serde(skip_serializing_if = "BTreeMap::is_empty", serialize_with = "string_keys")]
158    pub refs: BTreeMap<usize, ConversionInfo>,
159    /// Default (fallback) conversion, when it is itself a conversion.
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub default: Option<Box<ConversionInfo>>,
162}
163
164/// Serialize reference-index maps with string keys, so the JSON / JS object
165/// form is `{ "0": ..., "1": ... }`.
166fn string_keys<V: Serialize, S: serde::Serializer>(map: &BTreeMap<usize, V>, serializer: S) -> Result<S::Ok, S::Error> {
167    serializer.collect_map(map.iter().map(|(k, v)| (k.to_string(), v)))
168}
169
170impl From<&ConversionBlock> for ConversionInfo {
171    fn from(cc: &ConversionBlock) -> Self {
172        ConversionInfo {
173            conversion_type: format!("{:?}", cc.cc_type),
174            values: cc.cc_val.clone(),
175            precision: cc.cc_precision,
176            flags: cc.cc_flags,
177            physical_range: cc.cc_phy_range_min.zip(cc.cc_phy_range_max).map(|(a, b)| [a, b]),
178            formula: cc.formula.clone(),
179            texts: cc.resolved_texts.iter().flatten().map(|(k, v)| (*k, v.clone())).collect(),
180            refs: cc
181                .resolved_conversions
182                .iter()
183                .flatten()
184                .map(|(k, v)| (*k, ConversionInfo::from(v.as_ref())))
185                .collect(),
186            default: cc.default_conversion.as_deref().map(|d| Box::new(d.into())),
187        }
188    }
189}
190
191/// Options for `read` / `values`: which group to look in, and which part of
192/// the channel to read.
193///
194/// Select **either** a time window (`start_time` / `end_time`, inclusive, in
195/// the master channel's unit — seconds relative to the measurement start for
196/// a time master) **or** a record window (`start_record` / `record_count`).
197/// Omitted bounds are open.
198///
199/// ```
200/// use mf4_rs::ReadOptions;
201/// let opts = ReadOptions::new().group("Engine").time(Some(1.0), Some(2.5));
202/// let page = ReadOptions::new().records(1_000, 500);
203/// let stored = ReadOptions::new().raw(true); // skip the conversion
204/// ```
205///
206/// `raw` returns the values as stored in the file, without the channel's
207/// conversion (a linear channel gives its stored numbers, a value-to-text
208/// channel its keys instead of the texts). Only the requested channel is
209/// affected: `timestamps` and time windows still use the physical (converted)
210/// time axis. `unit` is the channel's (physical) unit, unchanged.
211#[derive(Debug, Clone, Default, PartialEq)]
212pub struct ReadOptions {
213    /// Group name, to disambiguate a channel name used by several groups.
214    pub group: Option<String>,
215    /// Inclusive lower time bound.
216    pub start_time: Option<f64>,
217    /// Inclusive upper time bound.
218    pub end_time: Option<f64>,
219    /// First record of a record window (0-based).
220    pub start_record: Option<u64>,
221    /// Number of records in a record window.
222    pub record_count: Option<u64>,
223    /// Return the stored values, without applying the channel's conversion.
224    pub raw: bool,
225}
226
227/// A validated [`ReadOptions`] window.
228#[derive(Debug, Clone, Copy, PartialEq)]
229pub(crate) enum Window {
230    /// The whole channel.
231    All,
232    /// Samples whose master value lies in `[start, end]`.
233    Time(Option<f64>, Option<f64>),
234    /// Records `[start, start + count)`; `None` count = to the end.
235    Records(u64, Option<u64>),
236}
237
238impl ReadOptions {
239    /// Options selecting the whole channel, first match across all groups.
240    pub fn new() -> Self {
241        Self::default()
242    }
243
244    /// Restrict the lookup to the group(s) with this name.
245    pub fn group(mut self, group: impl Into<String>) -> Self {
246        self.group = Some(group.into());
247        self
248    }
249
250    /// Select samples whose master (time) value lies in `[start, end]`.
251    pub fn time(mut self, start: Option<f64>, end: Option<f64>) -> Self {
252        self.start_time = start;
253        self.end_time = end;
254        self
255    }
256
257    /// Select records `[start, start + count)`.
258    pub fn records(mut self, start: u64, count: u64) -> Self {
259        self.start_record = Some(start);
260        self.record_count = Some(count);
261        self
262    }
263
264    /// Return the values as stored, without the channel's conversion.
265    pub fn raw(mut self, raw: bool) -> Self {
266        self.raw = raw;
267        self
268    }
269
270    /// Build options from the flat optional arguments the bindings take.
271    pub fn from_parts(
272        group: Option<&str>,
273        start_time: Option<f64>,
274        end_time: Option<f64>,
275        start_record: Option<u64>,
276        record_count: Option<u64>,
277    ) -> Self {
278        ReadOptions {
279            group: group.map(str::to_string),
280            start_time,
281            end_time,
282            start_record,
283            record_count,
284            raw: false,
285        }
286    }
287
288    /// The group filter as `Option<&str>`.
289    pub(crate) fn group_name(&self) -> Option<&str> {
290        self.group.as_deref()
291    }
292
293    /// Validate and classify the requested window.
294    pub(crate) fn window(&self) -> Result<Window, MdfError> {
295        let by_time = self.start_time.is_some() || self.end_time.is_some();
296        let by_record = self.start_record.is_some() || self.record_count.is_some();
297        if by_time && by_record {
298            return Err(MdfError::InvalidArgument(
299                "select either a time window (start_time/end_time) or a record window \
300                 (start_record/record_count), not both"
301                    .to_string(),
302            ));
303        }
304        if by_time {
305            for (label, v) in [("start_time", self.start_time), ("end_time", self.end_time)] {
306                if v.is_some_and(f64::is_nan) {
307                    return Err(MdfError::InvalidArgument(format!("{label} must not be NaN")));
308                }
309            }
310            return Ok(Window::Time(self.start_time, self.end_time));
311        }
312        if by_record {
313            return Ok(Window::Records(self.start_record.unwrap_or(0), self.record_count));
314        }
315        Ok(Window::All)
316    }
317}
318
319/// Resolve a record window against `total` records, returning
320/// `(start, count)`. Errors when the window reaches past the last record.
321pub(crate) fn resolve_records(start: u64, count: Option<u64>, total: u64) -> Result<(u64, u64), MdfError> {
322    let count = count.unwrap_or_else(|| total.saturating_sub(start));
323    match start.checked_add(count) {
324        Some(end) if end <= total => Ok((start, count)),
325        _ => Err(MdfError::InvalidArgument(format!(
326            "record window starting at {start} for {count} records exceeds the group's {total} records"
327        ))),
328    }
329}
330
331/// Records probed per round of [`search_time_window`].
332const TIME_SEARCH_FANOUT: u64 = 16;
333
334/// Record window `(start, count)` of a time axis of `n` records whose values
335/// lie in `[t_start, t_end]` (either bound optional), reading values only
336/// through `probe(record)`.
337///
338/// The axis must be non-decreasing, as MDF requires of a time master. It is
339/// searched, not scanned: each round probes up to [`TIME_SEARCH_FANOUT`]
340/// records per bound, so a window costs about `log16(n)` rounds. Every probed
341/// value is checked against the others; a pair out of order (a time axis that
342/// resets or jumps backwards) is refused with [`MdfError::InvalidArgument`]
343/// rather than silently selecting an arbitrary part of the data. `NaN` (an
344/// invalid time sample) is not checked.
345///
346/// Both bounds' probes of a round are attempted before the first error is
347/// returned, so a probing reader (the batched / wasm fragment drivers)
348/// records every gap of a round in one pass. `Mdf` (probes decoded from memory) and
349/// `MdfIndex` (probes fetched from the source) share this function, so they
350/// select identical records.
351pub(crate) fn search_time_window(
352    n: u64,
353    t_start: Option<f64>,
354    t_end: Option<f64>,
355    mut probe: impl FnMut(u64) -> Result<f64, MdfError>,
356) -> Result<(u64, u64), MdfError> {
357    // first record with t >= t_start; first record with t > t_end
358    let mut lo = Bound::new(n);
359    let mut hi = Bound::new(n);
360    if t_start.is_none() {
361        lo.done_at(0);
362    }
363    if t_end.is_none() {
364        hi.done_at(n);
365    }
366    let mut seen: Vec<(u64, f64)> = Vec::new();
367    while !(lo.done() && hi.done()) {
368        let mut first_err = None;
369        for (bound, below) in [
370            (&mut lo, &(|v: f64| t_start.is_some_and(|t| v < t)) as &dyn Fn(f64) -> bool),
371            (&mut hi, &|v: f64| t_end.is_some_and(|t| v <= t)),
372        ] {
373            if bound.done() {
374                continue;
375            }
376            let probes = bound.probes();
377            let mut below_flags = Vec::with_capacity(probes.len());
378            for &p in &probes {
379                match probe(p) {
380                    Ok(v) => {
381                        seen.push((p, v));
382                        below_flags.push(below(v));
383                    }
384                    Err(e) => {
385                        first_err.get_or_insert(e);
386                    }
387                }
388            }
389            if below_flags.len() == probes.len() {
390                bound.narrow(&probes, &below_flags);
391            }
392        }
393        if let Some(e) = first_err {
394            return Err(e);
395        }
396        check_non_decreasing(&mut seen)?;
397    }
398    let (start, end) = (lo.lo, hi.lo.max(lo.lo));
399    Ok((start, end - start))
400}
401
402/// Refuse a time axis whose probed values are out of order.
403fn check_non_decreasing(seen: &mut Vec<(u64, f64)>) -> Result<(), MdfError> {
404    seen.sort_by_key(|&(i, _)| i);
405    seen.dedup_by_key(|&mut (i, _)| i);
406    let mut prev: Option<(u64, f64)> = None;
407    for &(i, v) in seen.iter() {
408        if v.is_nan() {
409            continue;
410        }
411        if let Some((pi, pv)) = prev
412            && v < pv
413        {
414            return Err(MdfError::InvalidArgument(format!(
415                "the time axis is not monotonic (record {pi} is {pv}, record {i} is {v}); \
416                 a time window needs a non-decreasing master channel — select a record \
417                 window (start_record / record_count) instead"
418            )));
419        }
420        prev = Some((i, v));
421    }
422    Ok(())
423}
424
425/// State of one partition-point search over `[lo, hi)`: the answer is the
426/// first record for which the predicate ("still below the bound") is false.
427struct Bound {
428    lo: u64,
429    hi: u64,
430}
431
432impl Bound {
433    fn new(n: u64) -> Self {
434        Bound { lo: 0, hi: n }
435    }
436
437    fn done(&self) -> bool {
438        self.lo >= self.hi
439    }
440
441    fn done_at(&mut self, at: u64) {
442        self.lo = at;
443        self.hi = at;
444    }
445
446    /// Up to [`TIME_SEARCH_FANOUT`] distinct, increasing records in `[lo, hi)`.
447    fn probes(&self) -> Vec<u64> {
448        let span = self.hi - self.lo;
449        if span <= TIME_SEARCH_FANOUT {
450            return (self.lo..self.hi).collect();
451        }
452        (0..TIME_SEARCH_FANOUT)
453            .map(|i| self.lo + (i as u128 * span as u128 / TIME_SEARCH_FANOUT as u128) as u64)
454            .collect()
455    }
456
457    /// Narrow to the gap between the last probe below the bound and the first
458    /// one not below it (values are non-decreasing).
459    fn narrow(&mut self, probes: &[u64], below: &[bool]) {
460        match below.iter().position(|b| !b) {
461            Some(0) => self.hi = probes[0],
462            Some(j) => {
463                self.lo = probes[j - 1] + 1;
464                self.hi = probes[j];
465            }
466            None => self.lo = probes[probes.len() - 1] + 1,
467        }
468    }
469}