use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::blocks::conversion::ConversionBlock;
use crate::error::MdfError;
use crate::signal::Signal;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelInfo {
pub name: Option<String>,
pub unit: Option<String>,
pub comment: Option<String>,
pub data_type: String,
pub bit_count: u32,
pub is_master: bool,
pub is_vlsd: bool,
pub has_conversion: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupInfo {
pub name: Option<String>,
pub comment: Option<String>,
pub record_count: u64,
pub channel_names: Vec<String>,
pub master_channel: Option<String>,
pub channels: Vec<ChannelInfo>,
}
impl GroupInfo {
pub fn channel(&self, name: &str) -> Option<&ChannelInfo> {
self.channels.iter().find(|c| c.name.as_deref() == Some(name))
}
}
pub(crate) fn logical_group_members(
names: &[Option<String>],
time_groups: &[Option<usize>],
channel_counts: &[usize],
first: usize,
) -> Vec<usize> {
let Some(time_group) = time_groups[first] else {
if channel_counts[first] != 1 {
return vec![first];
}
return (0..names.len())
.filter(|&h| names[h] == names[first] && time_groups[h].is_none() && channel_counts[h] == 1)
.collect();
};
let mut members = Vec::new();
if names[time_group] != names[first] {
members.push(time_group);
}
members.extend(
(0..names.len()).filter(|&h| names[h] == names[first] && time_groups[h] == Some(time_group)),
);
members
}
pub(crate) fn merge_group_infos(first: GroupInfo, members: impl IntoIterator<Item = GroupInfo>) -> GroupInfo {
let mut merged = GroupInfo { channel_names: Vec::new(), channels: Vec::new(), ..first };
for info in members {
merged.channel_names.extend(info.channel_names);
merged.channels.extend(info.channels);
}
merged
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct TimeRange {
pub start: f64,
pub end: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConversionInfo {
#[serde(rename = "type")]
pub conversion_type: String,
pub values: Vec<f64>,
pub precision: u8,
pub flags: u16,
#[serde(skip_serializing_if = "Option::is_none")]
pub physical_range: Option<[f64; 2]>,
#[serde(skip_serializing_if = "Option::is_none")]
pub formula: Option<String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty", serialize_with = "string_keys")]
pub texts: BTreeMap<usize, String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty", serialize_with = "string_keys")]
pub refs: BTreeMap<usize, ConversionInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<Box<ConversionInfo>>,
}
fn string_keys<V: Serialize, S: serde::Serializer>(map: &BTreeMap<usize, V>, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_map(map.iter().map(|(k, v)| (k.to_string(), v)))
}
impl From<&ConversionBlock> for ConversionInfo {
fn from(cc: &ConversionBlock) -> Self {
ConversionInfo {
conversion_type: format!("{:?}", cc.cc_type),
values: cc.cc_val.clone(),
precision: cc.cc_precision,
flags: cc.cc_flags,
physical_range: cc.cc_phy_range_min.zip(cc.cc_phy_range_max).map(|(a, b)| [a, b]),
formula: cc.formula.clone(),
texts: cc.resolved_texts.iter().flatten().map(|(k, v)| (*k, v.clone())).collect(),
refs: cc
.resolved_conversions
.iter()
.flatten()
.map(|(k, v)| (*k, ConversionInfo::from(v.as_ref())))
.collect(),
default: cc.default_conversion.as_deref().map(|d| Box::new(d.into())),
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ReadOptions {
pub group: Option<String>,
pub start_time: Option<f64>,
pub end_time: Option<f64>,
pub start_record: Option<u64>,
pub record_count: Option<u64>,
pub raw: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum Window {
All,
Time(Option<f64>, Option<f64>),
Records(u64, Option<u64>),
}
impl ReadOptions {
pub fn new() -> Self {
Self::default()
}
pub fn group(mut self, group: impl Into<String>) -> Self {
self.group = Some(group.into());
self
}
pub fn time(mut self, start: Option<f64>, end: Option<f64>) -> Self {
self.start_time = start;
self.end_time = end;
self
}
pub fn records(mut self, start: u64, count: u64) -> Self {
self.start_record = Some(start);
self.record_count = Some(count);
self
}
pub fn raw(mut self, raw: bool) -> Self {
self.raw = raw;
self
}
pub fn from_parts(
group: Option<&str>,
start_time: Option<f64>,
end_time: Option<f64>,
start_record: Option<u64>,
record_count: Option<u64>,
) -> Self {
ReadOptions {
group: group.map(str::to_string),
start_time,
end_time,
start_record,
record_count,
raw: false,
}
}
pub(crate) fn group_name(&self) -> Option<&str> {
self.group.as_deref()
}
pub(crate) fn window(&self) -> Result<Window, MdfError> {
let by_time = self.start_time.is_some() || self.end_time.is_some();
let by_record = self.start_record.is_some() || self.record_count.is_some();
if by_time && by_record {
return Err(MdfError::InvalidArgument(
"select either a time window (start_time/end_time) or a record window \
(start_record/record_count), not both"
.to_string(),
));
}
if by_time {
for (label, v) in [("start_time", self.start_time), ("end_time", self.end_time)] {
if v.is_some_and(f64::is_nan) {
return Err(MdfError::InvalidArgument(format!("{label} must not be NaN")));
}
}
return Ok(Window::Time(self.start_time, self.end_time));
}
if by_record {
return Ok(Window::Records(self.start_record.unwrap_or(0), self.record_count));
}
Ok(Window::All)
}
}
pub(crate) fn resolve_records(start: u64, count: Option<u64>, total: u64) -> Result<(u64, u64), MdfError> {
let count = count.unwrap_or_else(|| total.saturating_sub(start));
match start.checked_add(count) {
Some(end) if end <= total => Ok((start, count)),
_ => Err(MdfError::InvalidArgument(format!(
"record window starting at {start} for {count} records exceeds the group's {total} records"
))),
}
}
pub(crate) fn slice_signal(mut signal: Signal, window: Window, is_master: bool) -> Result<Signal, MdfError> {
let total = if signal.timestamps.is_empty() {
signal.values.len()
} else {
signal.values.len().min(signal.timestamps.len())
};
let (start, count) = match window {
Window::All => return Ok(signal),
Window::Records(start, count) => resolve_records(start, count, total as u64)?,
Window::Time(t0, t1) => {
let own_values;
let axis: &[f64] = if !signal.timestamps.is_empty() {
&signal.timestamps[..total]
} else if is_master {
own_values = signal.values_f64();
&own_values
} else if signal.values.is_empty() {
&[]
} else {
return Err(MdfError::InvalidArgument(format!(
"channel '{}' has no master (time) channel; cannot select by time",
signal.name
)));
};
search_time_window(axis.len() as u64, t0, t1, |i| Ok(axis[i as usize]))?
}
};
let (s, e) = (start as usize, (start + count) as usize);
signal.values.truncate(e);
signal.values.drain(..s);
if !signal.timestamps.is_empty() {
signal.timestamps.truncate(e);
signal.timestamps.drain(..s);
}
Ok(signal)
}
const TIME_SEARCH_FANOUT: u64 = 16;
pub(crate) fn search_time_window(
n: u64,
t_start: Option<f64>,
t_end: Option<f64>,
mut probe: impl FnMut(u64) -> Result<f64, MdfError>,
) -> Result<(u64, u64), MdfError> {
let mut lo = Bound::new(n);
let mut hi = Bound::new(n);
if t_start.is_none() {
lo.done_at(0);
}
if t_end.is_none() {
hi.done_at(n);
}
let mut seen: Vec<(u64, f64)> = Vec::new();
while !(lo.done() && hi.done()) {
let mut first_err = None;
for (bound, below) in [
(&mut lo, &(|v: f64| t_start.is_some_and(|t| v < t)) as &dyn Fn(f64) -> bool),
(&mut hi, &|v: f64| t_end.is_some_and(|t| v <= t)),
] {
if bound.done() {
continue;
}
let probes = bound.probes();
let mut below_flags = Vec::with_capacity(probes.len());
for &p in &probes {
match probe(p) {
Ok(v) => {
seen.push((p, v));
below_flags.push(below(v));
}
Err(e) => {
first_err.get_or_insert(e);
}
}
}
if below_flags.len() == probes.len() {
bound.narrow(&probes, &below_flags);
}
}
if let Some(e) = first_err {
return Err(e);
}
check_non_decreasing(&mut seen)?;
}
let (start, end) = (lo.lo, hi.lo.max(lo.lo));
Ok((start, end - start))
}
fn check_non_decreasing(seen: &mut Vec<(u64, f64)>) -> Result<(), MdfError> {
seen.sort_by_key(|&(i, _)| i);
seen.dedup_by_key(|&mut (i, _)| i);
let mut prev: Option<(u64, f64)> = None;
for &(i, v) in seen.iter() {
if v.is_nan() {
continue;
}
if let Some((pi, pv)) = prev
&& v < pv
{
return Err(MdfError::InvalidArgument(format!(
"the time axis is not monotonic (record {pi} is {pv}, record {i} is {v}); \
a time window needs a non-decreasing master channel — select a record \
window (start_record / record_count) instead"
)));
}
prev = Some((i, v));
}
Ok(())
}
struct Bound {
lo: u64,
hi: u64,
}
impl Bound {
fn new(n: u64) -> Self {
Bound { lo: 0, hi: n }
}
fn done(&self) -> bool {
self.lo >= self.hi
}
fn done_at(&mut self, at: u64) {
self.lo = at;
self.hi = at;
}
fn probes(&self) -> Vec<u64> {
let span = self.hi - self.lo;
if span <= TIME_SEARCH_FANOUT {
return (self.lo..self.hi).collect();
}
(0..TIME_SEARCH_FANOUT)
.map(|i| self.lo + (i as u128 * span as u128 / TIME_SEARCH_FANOUT as u128) as u64)
.collect()
}
fn narrow(&mut self, probes: &[u64], below: &[bool]) {
match below.iter().position(|b| !b) {
Some(0) => self.hi = probes[0],
Some(j) => {
self.lo = probes[j - 1] + 1;
self.hi = probes[j];
}
None => self.lo = probes[probes.len() - 1] + 1,
}
}
}