Implement AssertEq for reference types

Just as the standard library's PartialEq is implemented for reference types,
the ApproxEq trait should be implemented on them as well. This is mostly an
ergonomic improvement for certain testing situations, where a method yields a
reference. For non-copy types it allows using the assert_approx_… macros, which
would otherwise not be possible.
This commit is contained in:
Eduard Bopp 2015-01-25 19:51:07 +01:00
parent bbf5ed17e4
commit 5ca3e41375
2 changed files with 39 additions and 0 deletions

View File

@ -231,6 +231,42 @@ impl ApproxEq<f64> for f64 {
}
}
impl<'a, N, T: ApproxEq<N>> ApproxEq<N> for &'a T {
fn approx_epsilon(_: Option<&'a T>) -> N {
ApproxEq::approx_epsilon(None::<T>)
}
fn approx_eq_eps(&self, other: &&'a T, approx_epsilon: &N) -> bool {
ApproxEq::approx_eq_eps(*self, *other, approx_epsilon)
}
fn approx_ulps(_: Option<&'a T>) -> u32 {
ApproxEq::approx_ulps(None::<T>)
}
fn approx_eq_ulps(&self, other: &&'a T, ulps: u32) -> bool {
ApproxEq::approx_eq_ulps(*self, *other, ulps)
}
}
impl<'a, N, T: ApproxEq<N>> ApproxEq<N> for &'a mut T {
fn approx_epsilon(_: Option<&'a mut T>) -> N {
ApproxEq::approx_epsilon(None::<T>)
}
fn approx_eq_eps(&self, other: &&'a mut T, approx_epsilon: &N) -> bool {
ApproxEq::approx_eq_eps(*self, *other, approx_epsilon)
}
fn approx_ulps(_: Option<&'a mut T>) -> u32 {
ApproxEq::approx_ulps(None::<T>)
}
fn approx_eq_ulps(&self, other: &&'a mut T, ulps: u32) -> bool {
ApproxEq::approx_eq_ulps(*self, *other, ulps)
}
}
/// Trait of objects having an absolute value.
/// This is useful if the object does not have the same type as its absolute value.
pub trait Absolute<A> {

View File

@ -13,6 +13,7 @@ fn assert_approx_eq_f64() {
let a = 1.0f64;
let b = 1.0f64 + 1.0e-12f64;
assert_approx_eq!(a, b);
assert_approx_eq!(&a, &b);
}
#[test]
@ -26,6 +27,7 @@ fn assert_approx_eq_vec2_f32_fail() {
#[test]
fn assert_approx_eq_eps_f32() {
assert_approx_eq_eps!(1.0f32, 1.1, 0.2);
assert_approx_eq_eps!(&mut 1.0f32, &mut 1.1, 0.2);
}
#[test]
@ -40,6 +42,7 @@ fn assert_approx_eq_ulps_f32() {
let y = 1000000.1_f32;
assert!(x != y);
assert_approx_eq_ulps!(x, y, 3);
assert_approx_eq_ulps!(&x, &y, 3);
}
#[test]