use labstream_wire::{Format, Value};
mod sealed {
pub trait Sealed {}
}
pub trait Scalar: Copy + Default + sealed::Sealed {
const FORMAT: Format;
fn from_value(v: &Value) -> Self;
fn into_value(self) -> Value;
}
macro_rules! scalar {
($t:ty, $fmt:ident, $var:ident) => {
impl sealed::Sealed for $t {}
impl Scalar for $t {
const FORMAT: Format = Format::$fmt;
fn from_value(v: &Value) -> Self {
match *v {
Value::F32(x) => x as $t,
Value::F64(x) => x as $t,
Value::I8(x) => x as $t,
Value::I16(x) => x as $t,
Value::I32(x) => x as $t,
Value::I64(x) => x as $t,
Value::Str(_) => <$t>::default(),
}
}
fn into_value(self) -> Value {
Value::$var(self)
}
}
};
}
scalar!(f32, Float32, F32);
scalar!(f64, Double64, F64);
scalar!(i8, Int8, I8);
scalar!(i16, Int16, I16);
scalar!(i32, Int32, I32);
scalar!(i64, Int64, I64);
pub fn as_f64(v: &Value) -> Option<f64> {
Some(match *v {
Value::F32(x) => x as f64,
Value::F64(x) => x,
Value::I8(x) => x as f64,
Value::I16(x) => x as f64,
Value::I32(x) => x as f64,
Value::I64(x) => x as f64,
Value::Str(_) => return None,
})
}
pub fn as_text(v: &Value) -> String {
match v {
Value::Str(b) => String::from_utf8_lossy(b).into_owned(),
other => as_f64(other).map(|n| n.to_string()).unwrap_or_default(),
}
}