use crate::error::UcumError;
use crate::{Analysis, Dimension};
#[derive(Clone, Debug, PartialEq)]
pub struct Quantity {
pub value: f64,
pub unit: String,
}
impl Quantity {
pub fn new(value: f64, unit: impl Into<String>) -> Self {
Quantity {
value,
unit: unit.into(),
}
}
pub fn analyze(&self) -> Result<Analysis, UcumError> {
crate::analyze(&self.unit)
}
pub fn dimension(&self) -> Result<Dimension, UcumError> {
Ok(self.analyze()?.dimension)
}
pub fn is_comparable(&self, unit: &str) -> Result<bool, UcumError> {
crate::is_comparable(&self.unit, unit)
}
pub fn mul(&self, other: &Quantity) -> Quantity {
Quantity {
value: self.value * other.value,
unit: format!("{}.{}", group(&self.unit), group(&other.unit)),
}
}
pub fn div(&self, other: &Quantity) -> Quantity {
Quantity {
value: self.value / other.value,
unit: format!("{}/{}", group(&self.unit), group(&other.unit)),
}
}
pub fn convert_to(&self, unit: &str) -> Result<Quantity, UcumError> {
Ok(Quantity {
value: crate::convert(self.value, &self.unit, unit)?,
unit: unit.to_string(),
})
}
}
fn group(unit: &str) -> String {
if unit.trim().is_empty() {
"1".to_string()
} else {
format!("({unit})")
}
}