Skip to content

Commit

Permalink
Custom PartialEq impl for numbers and support for comparisons of di…
Browse files Browse the repository at this point in the history
…fferent units
  • Loading branch information
frectonz committed Mar 3, 2024
1 parent 0e8e192 commit c3e7795
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
7 changes: 6 additions & 1 deletion core/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,12 @@ pub(crate) fn evaluate<I: Interrupt>(
let lhs = evaluate(*a, scope.clone(), attrs, context, int)?;
let rhs = evaluate(*b, scope.clone(), attrs, context, int)?;

Value::Bool(if is_equals { lhs == rhs } else { lhs != rhs })
if let (Value::Num(l), Value::Num(r)) = (&lhs, &rhs) {
let a = l.clone().sub(*r.clone(), int)?;
Value::Bool(if is_equals { a.is_zero() } else { !a.is_zero() })
} else {
Value::Bool(if is_equals { lhs == rhs } else { lhs != rhs })
}
}
})
}
Expand Down
8 changes: 7 additions & 1 deletion core/src/num/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use unit_exponent::UnitExponent;

use super::Exact;

#[derive(Clone, PartialEq, Eq)]
#[derive(Clone, Eq)]
#[allow(clippy::pedantic)]
pub(crate) struct Value {
#[allow(clippy::struct_field_names)]
Expand All @@ -37,6 +37,12 @@ pub(crate) struct Value {
simplifiable: bool,
}

impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.unit == other.unit
}

Check warning on line 43 in core/src/num/unit.rs

View check run for this annotation

Codecov / codecov/patch

core/src/num/unit.rs#L41-L43

Added lines #L41 - L43 were not covered by tests
}

impl Value {
pub(crate) fn serialize(&self, write: &mut impl io::Write) -> FResult<()> {
self.value.serialize(write)?;
Expand Down
1 change: 1 addition & 0 deletions core/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5880,4 +5880,5 @@ fn test_equality() {
test_eval("1 + 2 != 4", "true");
test_eval("true == false", "false");
test_eval("true != false", "true");
test_eval("2m == 200cm", "true");
}

0 comments on commit c3e7795

Please sign in to comment.