euclid/
approxeq.rs

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    fn approx_epsilon() -> Eps;
13    fn approx_eq(&self, other: &Self) -> bool;
14    fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
15}
16
17macro_rules! approx_eq {
18    ($ty:ty, $eps:expr) => (
19        impl ApproxEq<$ty> for $ty {
20            #[inline]
21            fn approx_epsilon() -> $ty { $eps }
22            #[inline]
23            fn approx_eq(&self, other: &$ty) -> bool {
24                self.approx_eq_eps(other, &$eps)
25            }
26            #[inline]
27            fn approx_eq_eps(&self, other: &$ty, approx_epsilon: &$ty) -> bool {
28                (*self - *other).abs() < *approx_epsilon
29            }
30        }
31    )
32}
33
34approx_eq!(f32, 1.0e-6);
35approx_eq!(f64, 1.0e-6);