From 5ca3e4137526a5bc7b573774d561889dd72760c5 Mon Sep 17 00:00:00 2001 From: Eduard Bopp Date: Sun, 25 Jan 2015 19:51:07 +0100 Subject: [PATCH] Implement AssertEq for reference types MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/traits/operations.rs | 36 ++++++++++++++++++++++++++++++++++++ tests/assert.rs | 3 +++ 2 files changed, 39 insertions(+) diff --git a/src/traits/operations.rs b/src/traits/operations.rs index 14e0845f..1c58f390 100644 --- a/src/traits/operations.rs +++ b/src/traits/operations.rs @@ -231,6 +231,42 @@ impl ApproxEq for f64 { } } +impl<'a, N, T: ApproxEq> ApproxEq for &'a T { + fn approx_epsilon(_: Option<&'a T>) -> N { + ApproxEq::approx_epsilon(None::) + } + + 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::) + } + + fn approx_eq_ulps(&self, other: &&'a T, ulps: u32) -> bool { + ApproxEq::approx_eq_ulps(*self, *other, ulps) + } +} + +impl<'a, N, T: ApproxEq> ApproxEq for &'a mut T { + fn approx_epsilon(_: Option<&'a mut T>) -> N { + ApproxEq::approx_epsilon(None::) + } + + 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::) + } + + 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 { diff --git a/tests/assert.rs b/tests/assert.rs index 0b0ebcee..2be736dc 100644 --- a/tests/assert.rs +++ b/tests/assert.rs @@ -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]