1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use num::{Float, Zero};
use std::fmt::{self, Debug, Display, Formatter};
use crate::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, epsilon }
}