Skip to content

Commit

Permalink
Fix issue #20 with saturating_abs macros [to use std fns once stablized]
Browse files Browse the repository at this point in the history
  • Loading branch information
mikedilger committed Jul 28, 2019
1 parent 17e4231 commit 4544be1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/eq.rs
Expand Up @@ -99,7 +99,7 @@ impl ApproxEq for f32 {
{
// Perform ulps comparion last
let diff: i32 = self.ulps(&other);
diff.abs() <= margin.ulps
saturating_abs_i32!(diff) <= margin.ulps
}
}
}
Expand Down Expand Up @@ -227,7 +227,7 @@ impl ApproxEq for f64 {
{
// Perform ulps comparion last
let diff: i64 = self.ulps(&other);
diff.abs() <= margin.ulps
saturating_abs_i64!(diff) <= margin.ulps
}
}
}
Expand Down Expand Up @@ -277,3 +277,7 @@ fn f64_approx_eq_test6() {
println!("Ulps Difference: {}",x.ulps(&y));
assert!(x.approx_eq(y, (0.0, 3)) == true);
}
#[test]
fn f64_code_triggering_issue_20() {
assert_eq!((-25.0f64).approx_eq(25.0, (0.00390625, 1)), false);
}
26 changes: 26 additions & 0 deletions src/macros.rs
Expand Up @@ -20,6 +20,32 @@ macro_rules! approx_eq {
};
}

// Until saturating_abs() comes out of nightly, we have to code it ourselves.
macro_rules! saturating_abs_i32 {
($val:expr) => {
if $val.is_negative() {
match $val.checked_neg() {
Some(v) => v,
None => std::i32::MAX
}
} else {
$val
}
};
}
macro_rules! saturating_abs_i64 {
($val:expr) => {
if $val.is_negative() {
match $val.checked_neg() {
Some(v) => v,
None => std::i64::MAX
}
} else {
$val
}
};
}

#[test]
fn test_macro() {
let a: f32 = 0.15 + 0.15 + 0.15;
Expand Down

0 comments on commit 4544be1

Please sign in to comment.