use crate::{AmountT, Quantity};
pub trait Converter<Q: Quantity> {
fn convert(self, qty: &Q, to_unit: Q::UnitType) -> Option<Q>;
}
#[derive(Debug)]
pub struct ConversionTable<Q: Quantity, const N: usize> {
pub mappings: [(Q::UnitType, Q::UnitType, AmountT, AmountT); N],
}
impl<Q: Quantity, const N: usize> Converter<Q> for ConversionTable<Q, N> {
fn convert(self, qty: &Q, to_unit: Q::UnitType) -> Option<Q> {
if (*qty).unit() == to_unit {
return Some(*qty);
}
self.mappings.iter().find_map(|(from, to, factor, offset)| {
(*from == (*qty).unit() && *to == to_unit)
.then(|| Q::new(qty.amount() * factor + offset, to_unit))
})
}
}