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))
}
}
#[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>,
}
#[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 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,
}
}
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
)));
};
let lo = t0.map_or(0, |t| axis.partition_point(|v| *v < t));
let hi = t1.map_or(axis.len(), |t| axis.partition_point(|v| *v <= t));
(lo as u64, hi.saturating_sub(lo) as u64)
}
};
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)
}