1// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10/// Trait for testing approximate equality
11pub trait ApproxEq<Eps> {
12 /// Default epsilon value
13 fn approx_epsilon() -> Eps;
14
15 /// Returns `true` is this object is approximately equal to the other one, using
16 /// a provided epsilon value.
17 fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
18
19 /// Returns `true` is this object is approximately equal to the other one, using
20 /// the `approx_epsilon()` epsilon value.
21 fn approx_eq(&self, other: &Self) -> bool {
22 self.approx_eq_eps(other, &Self::approx_epsilon())
23 }
24}
25
26macro_rules! approx_eq {
27 ($ty:ty, $eps:expr) => {
28 impl ApproxEq<$ty> for $ty {
29 #[inline]
30 fn approx_epsilon() -> $ty {
31 $eps
32 }
33 #[inline]
34 fn approx_eq_eps(&self, other: &$ty, approx_epsilon: &$ty) -> bool {
35 num_traits::Float::abs(*self - *other) < *approx_epsilon
36 }
37 }
38 };
39}
40
41approx_eq!(f32, 1.0e-6);
42approx_eq!(f64, 1.0e-6);
43