diff --git a/src/quantity/mod.rs b/src/quantity/mod.rs index 752b797..dcceb98 100644 --- a/src/quantity/mod.rs +++ b/src/quantity/mod.rs @@ -92,7 +92,12 @@ impl Add for Quantity { let number = self.number + rhs.number; let unit = self.unit; - let use_derived_unit = rhs.use_derived_unit; + let mut use_derived_unit = self.use_derived_unit.clone(); + for d in &rhs.use_derived_unit { + if !use_derived_unit.contains(d) { + use_derived_unit.push(d.clone()); + } + } Ok(Quantity { number, @@ -112,7 +117,12 @@ impl Sub for Quantity { let number = self.number - rhs.number; let unit = self.unit; - let use_derived_unit = rhs.use_derived_unit; + let mut use_derived_unit = self.use_derived_unit.clone(); + for d in &rhs.use_derived_unit { + if !use_derived_unit.contains(d) { + use_derived_unit.push(d.clone()); + } + } Ok(Quantity { number, @@ -128,7 +138,12 @@ impl Mul for Quantity { fn mul(self, rhs: Self) -> Self::Output { let number = self.number * rhs.number; let unit = self.unit * rhs.unit; - let use_derived_unit = rhs.use_derived_unit; + let mut use_derived_unit = Vec::new(); + for lhs_d in &self.use_derived_unit { + for rhs_d in &rhs.use_derived_unit { + use_derived_unit.push(lhs_d.clone() * rhs_d.clone()); + } + } Quantity { number, @@ -144,7 +159,12 @@ impl Div for Quantity { fn div(self, rhs: Self) -> Self::Output { let number = self.number / rhs.number; let unit = self.unit / rhs.unit; - let use_derived_unit = rhs.use_derived_unit; + let mut use_derived_unit = Vec::new(); + for lhs_d in &self.use_derived_unit { + for rhs_d in &rhs.use_derived_unit { + use_derived_unit.push(lhs_d.clone() / rhs_d.clone()); + } + } Quantity { number, diff --git a/src/quantity/units.rs b/src/quantity/units.rs index 14c96f0..1950b29 100644 --- a/src/quantity/units.rs +++ b/src/quantity/units.rs @@ -76,6 +76,32 @@ pub struct DerivedUnit { pub exponents: UnitCombo, } +impl Mul for DerivedUnit { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + DerivedUnit { + symbol: format!("{}*{}", self.symbol, rhs.symbol), + offset: self.offset * rhs.scale.clone() + rhs.offset, + scale: self.scale * rhs.scale, + exponents: self.exponents * rhs.exponents, + } + } +} + +impl Div for DerivedUnit { + type Output = Self; + + fn div(self, rhs: Self) -> Self::Output { + DerivedUnit { + symbol: format!("{}/{}", self.symbol, rhs.symbol), + offset: self.offset * rhs.scale.clone() - rhs.offset, + scale: self.scale / rhs.scale, + exponents: self.exponents / rhs.exponents, + } + } +} + impl Display for DerivedUnit { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.symbol)