use std::str;
use crate::parser::DbcError;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MultiplexIndicator {
Multiplexor,
MultiplexedSignal(u64),
MultiplexorAndMultiplexedSignal(u64),
Plain,
}
impl TryFrom<&str> for MultiplexIndicator {
type Error = DbcError;
fn try_from(text: &str) -> Result<Self, Self::Error> {
if text == "M" {
return Ok(Self::Multiplexor);
}
if let Some(text) = text.strip_prefix('m') {
if text.is_empty() {
return Ok(Self::Plain);
} else if let Some(text) = text.strip_suffix('M') {
if let Ok(value) = text.parse::<u64>() {
return Ok(Self::MultiplexorAndMultiplexedSignal(value));
}
} else if let Ok(value) = text.parse::<u64>() {
return Ok(Self::MultiplexedSignal(value));
}
}
Err(Self::Error::UnknownMultiplexIndicator(text.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn multiplexer_indicator_test() {
let val: MultiplexIndicator = "m34920".try_into().unwrap();
assert_eq!(val, MultiplexIndicator::MultiplexedSignal(34920));
let val: MultiplexIndicator = "M".try_into().unwrap();
assert_eq!(val, MultiplexIndicator::Multiplexor);
let val: MultiplexIndicator = "m8M".try_into().unwrap();
assert_eq!(val, MultiplexIndicator::MultiplexorAndMultiplexedSignal(8));
}
}