use num::{Float, Zero};
use std::fmt::{self, Display, Debug, Formatter};
use core::*;
pub struct CloseTo<T> {
expected: T,
epsilon: T,
}
impl<T: Debug> Display for CloseTo<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.expected.fmt(f)
}
}
impl<T: Float + Zero + Debug> Matcher<T> for CloseTo<T> {
fn matches(&self, actual: T) -> MatchResult {
let a = self.expected.abs();
let b = actual.abs();
let d = (a - b).abs();
let close =
a == b
|| ((a == Zero::zero() || b == Zero::zero() || d < Float::min_positive_value()) &&
d < (self.epsilon * Float::min_positive_value()))
|| d / (a + b).min(Float::max_value()) < self.epsilon;
if close {
success()
} else {
Err(format!("was {:?}", actual))
}
}
}
pub fn close_to<T>(expected: T, epsilon: T) -> CloseTo<T> {
CloseTo {
expected: expected,
epsilon: epsilon,
}
}