Skip to content

Commit

Permalink
Allow adding zero regardless of units (#310)
Browse files Browse the repository at this point in the history
  • Loading branch information
printfn committed Sep 22, 2024
1 parent 3bb9390 commit e8351a9
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 140 deletions.
20 changes: 10 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 4 additions & 13 deletions core/src/num/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,9 @@ impl Value {
}

pub(crate) fn add<I: Interrupt>(self, rhs: Self, int: &I) -> FResult<Self> {
if rhs.is_zero(int)? {
return Ok(self);
}
let scale_factor = Unit::compute_scale_factor(&rhs.unit, &self.unit, int)?;
let scaled = Exact::new(rhs.value, rhs.exact)
.mul(&scale_factor.scale_1.apply(Dist::from), int)?
Expand Down Expand Up @@ -241,19 +244,7 @@ impl Value {
}

pub(crate) fn sub<I: Interrupt>(self, rhs: Self, int: &I) -> FResult<Self> {
let scale_factor = Unit::compute_scale_factor(&rhs.unit, &self.unit, int)?;
let scaled = Exact::new(rhs.value, rhs.exact)
.mul(&scale_factor.scale_1.apply(Dist::from), int)?
.div(&scale_factor.scale_2.apply(Dist::from), int)?;
let value = Exact::new(self.value, self.exact).add(&-scaled, int)?;
Ok(Self {
value: value.value,
unit: self.unit,
exact: self.exact && rhs.exact && value.exact,
base: self.base,
format: self.format,
simplifiable: self.simplifiable,
})
self.add(-rhs, int)
}

pub(crate) fn div<I: Interrupt>(self, rhs: Self, int: &I) -> FResult<Self> {
Expand Down
8 changes: 8 additions & 0 deletions core/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6033,3 +6033,11 @@ fn test_words() {
test_eval_simple("1000000000000000000000 to words", "one sextillion");
test_eval_simple("1000000000000000000000000 to words", "one septillion");
}

#[test]
fn test_plus_zero_ignore_units() {
test_eval("4m + 0", "4 m");
test_eval("4m + 0kg", "4 m");
test_eval("4m + (sin pi) kg", "4 m");
expect_error("4m + (sin (pi/2)) kg", Some("cannot convert from kg to m: units 'kilogram' and 'meter' are incompatible"));
}
Loading

0 comments on commit e8351a9

Please sign in to comment.