assertables/assert_f64/
assert_f64_eq.rs

1//! Assert a floating point 64-bit number is equal to another within f64::EPSILON.
2//!
3//! Pseudocode:<br>
4//! a = b
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//!
11//! let a: f64 = 1.0 / 3.0;
12//! let b: f64 = 0.3333333333333334;
13//! assert_f64_eq!(a, b);
14//! ```
15//!
16//! # Module macros
17//!
18//! * [`assert_f64_eq`](macro@crate::assert_f64_eq)
19//! * [`assert_f64_eq_as_result`](macro@crate::assert_f64_eq_as_result)
20//! * [`debug_assert_f64_eq`](macro@crate::debug_assert_f64_eq)
21
22/// Assert two floating point numbers are equal within f64::EPSILON.
23///
24/// Pseudocode:<br>
25/// a = b
26///
27/// * If true, return Result `Ok(())`.
28///
29/// * Otherwise, return Result `Err(message)`.
30///
31/// This macro is useful for runtime checks, such as checking parameters,
32/// or sanitizing inputs, or handling different results in different ways.
33///
34/// # Module macros
35///
36/// * [`assert_f64_eq`](macro@crate::assert_f64_eq)
37/// * [`assert_f64_eq_as_result`](macro@crate::assert_f64_eq_as_result)
38/// * [`debug_assert_f64_eq`](macro@crate::debug_assert_f64_eq)
39///
40#[macro_export]
41macro_rules! assert_f64_eq_as_result {
42    ($a:expr, $b:expr $(,)?) => {
43        match (&$a, &$b) {
44            (a, b) => {
45                if (a >= b && a - b < f64::EPSILON) || (a <= b && b - a < f64::EPSILON) {
46                    Ok(())
47                } else {
48                    Err(format!(
49                        concat!(
50                            "assertion failed: `assert_f64_eq!(a, b)`\n",
51                            "https://docs.rs/assertables/9.8.3/assertables/macro.assert_f64_eq.html\n",
52                            " a label: `{}`,\n",
53                            " a debug: `{}`,\n",
54                            " b label: `{}`,\n",
55                            " b debug: `{:?}`,\n",
56                            "    diff: `{}`,\n",
57                            "       ε: `{}`",
58                        ),
59                        stringify!($a),
60                        a,
61                        stringify!($b),
62                        b,
63                        a - b,
64                        f64::EPSILON,
65                    ))
66                }
67            }
68        }
69    };
70}
71
72#[cfg(test)]
73mod test_assert_f64_eq_as_result {
74    use crate::assert_f64::{EQ, EQ_GT, EQ_LT, GT, LT};
75    use std::sync::Once;
76
77    #[test]
78    fn eq() {
79        let a: f64 = EQ;
80        let b: f64 = EQ;
81        for _ in 0..1 {
82            let actual = assert_f64_eq_as_result!(a, b);
83            assert_eq!(actual.unwrap(), ());
84        }
85    }
86
87    #[test]
88    fn eq_once() {
89        static A: Once = Once::new();
90        fn a() -> f64 {
91            if A.is_completed() {
92                panic!("A.is_completed()")
93            } else {
94                A.call_once(|| {})
95            }
96            EQ
97        }
98
99        static B: Once = Once::new();
100        fn b() -> f64 {
101            if B.is_completed() {
102                panic!("B.is_completed()")
103            } else {
104                B.call_once(|| {})
105            }
106            EQ
107        }
108
109        assert_eq!(A.is_completed(), false);
110        assert_eq!(B.is_completed(), false);
111        let result = assert_f64_eq_as_result!(a(), b());
112        assert!(result.is_ok());
113        assert_eq!(A.is_completed(), true);
114        assert_eq!(B.is_completed(), true);
115    }
116
117    #[test]
118    fn eq_lt() {
119        let a: f64 = EQ;
120        let b: f64 = EQ_GT;
121        for _ in 0..1 {
122            let actual = assert_f64_eq_as_result!(a, b);
123            assert_eq!(actual.unwrap(), ());
124        }
125    }
126
127    #[test]
128    fn eq_lt_once() {
129        static A: Once = Once::new();
130        fn a() -> f64 {
131            if A.is_completed() {
132                panic!("A.is_completed()")
133            } else {
134                A.call_once(|| {})
135            }
136            EQ
137        }
138
139        static B: Once = Once::new();
140        fn b() -> f64 {
141            if B.is_completed() {
142                panic!("B.is_completed()")
143            } else {
144                B.call_once(|| {})
145            }
146            EQ_GT
147        }
148
149        assert_eq!(A.is_completed(), false);
150        assert_eq!(B.is_completed(), false);
151        let result = assert_f64_eq_as_result!(a(), b());
152        assert!(result.is_ok());
153        assert_eq!(A.is_completed(), true);
154        assert_eq!(B.is_completed(), true);
155    }
156
157    #[test]
158    fn eq_gt() {
159        let a: f64 = EQ;
160        let b: f64 = EQ_LT;
161        for _ in 0..1 {
162            let actual = assert_f64_eq_as_result!(a, b);
163            assert_eq!(actual.unwrap(), ());
164        }
165    }
166
167    #[test]
168    fn eq_gt_once() {
169        static A: Once = Once::new();
170        fn a() -> f64 {
171            if A.is_completed() {
172                panic!("A.is_completed()")
173            } else {
174                A.call_once(|| {})
175            }
176            EQ
177        }
178
179        static B: Once = Once::new();
180        fn b() -> f64 {
181            if B.is_completed() {
182                panic!("B.is_completed()")
183            } else {
184                B.call_once(|| {})
185            }
186            EQ_LT
187        }
188
189        assert_eq!(A.is_completed(), false);
190        assert_eq!(B.is_completed(), false);
191        let result = assert_f64_eq_as_result!(a(), b());
192        assert!(result.is_ok());
193        assert_eq!(A.is_completed(), true);
194        assert_eq!(B.is_completed(), true);
195    }
196
197    #[test]
198    fn lt() {
199        let a: f64 = EQ;
200        let b: f64 = GT;
201        let actual = assert_f64_eq_as_result!(a, b);
202        let message = concat!(
203            "assertion failed: `assert_f64_eq!(a, b)`\n",
204            "https://docs.rs/assertables/9.8.3/assertables/macro.assert_f64_eq.html\n",
205            " a label: `a`,\n",
206            " a debug: `0.3333333333333333`,\n",
207            " b label: `b`,\n",
208            " b debug: `0.3333333333333339`,\n",
209            "    diff: `-0.0000000000000006106226635438361`,\n",
210            "       ε: `0.0000000000000002220446049250313`",
211        );
212        assert_eq!(actual.unwrap_err(), message);
213    }
214
215    #[test]
216    fn gt() {
217        let a: f64 = EQ;
218        let b: f64 = LT;
219        let actual = assert_f64_eq_as_result!(a, b);
220        let message = concat!(
221            "assertion failed: `assert_f64_eq!(a, b)`\n",
222            "https://docs.rs/assertables/9.8.3/assertables/macro.assert_f64_eq.html\n",
223            " a label: `a`,\n",
224            " a debug: `0.3333333333333333`,\n",
225            " b label: `b`,\n",
226            " b debug: `0.3333333333333329`,\n",
227            "    diff: `0.0000000000000003885780586188048`,\n",
228            "       ε: `0.0000000000000002220446049250313`",
229        );
230        assert_eq!(actual.unwrap_err(), message);
231    }
232}
233
234/// Assert a floating point 64-bit number is equal to another within f64::EPSILON.
235///
236/// Pseudocode:<br>
237/// a = b
238///
239/// * If true, return `()`.
240///
241/// * Otherwise, call [`panic!`] with a message and the values of the
242///   expressions with their debug representations.
243///
244/// # Examples
245///
246/// ```rust
247/// use assertables::*;
248/// # use std::panic;
249///
250/// # fn main() {
251/// let a: f64 = 1.0 / 3.0;
252/// let b: f64 = 0.3333333333333335;
253/// assert_f64_eq!(a, b);
254///
255/// # let result = panic::catch_unwind(|| {
256/// // This will panic
257/// let a: f64 = 1.0 / 3.0;
258/// let b: f64 = 0.3333333333333339;
259/// assert_f64_eq!(a, b);
260/// # });
261/// // assertion failed: `assert_f64_eq!(a, b)`
262/// // https://docs.rs/assertables/…/assertables/macro.assert_f64_eq.html
263/// //  a label: `a`,
264/// //  a debug: `0.3333333333333333`,
265/// //  b label: `b`,
266/// //  b debug: `0.3333333333333339`,`
267/// //     diff: `-0.0000000000000006106226635438361`,
268/// //        ε: `0.0000000000000002220446049250313`
269/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
270/// # let message = concat!(
271/// #     "assertion failed: `assert_f64_eq!(a, b)`\n",
272/// #     "https://docs.rs/assertables/9.8.3/assertables/macro.assert_f64_eq.html\n",
273/// #     " a label: `a`,\n",
274/// #     " a debug: `0.3333333333333333`,\n",
275/// #     " b label: `b`,\n",
276/// #     " b debug: `0.3333333333333339`,\n",
277/// #     "    diff: `-0.0000000000000006106226635438361`,\n",
278/// #     "       ε: `0.0000000000000002220446049250313`",
279/// # );
280/// # assert_eq!(actual, message);
281/// # }
282/// ```
283///
284/// # Module macros
285///
286/// * [`assert_f64_eq`](macro@crate::assert_f64_eq)
287/// * [`assert_f64_eq_as_result`](macro@crate::assert_f64_eq_as_result)
288/// * [`debug_assert_f64_eq`](macro@crate::debug_assert_f64_eq)
289///
290#[macro_export]
291macro_rules! assert_f64_eq {
292    ($a:expr, $b:expr $(,)?) => {
293        match $crate::assert_f64_eq_as_result!($a, $b) {
294            Ok(()) => (),
295            Err(err) => panic!("{}", err),
296        }
297    };
298    ($a:expr, $b:expr, $($message:tt)+) => {
299        match $crate::assert_f64_eq_as_result!($a, $b) {
300            Ok(()) => (),
301            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
302        }
303    };
304}
305
306#[cfg(test)]
307mod test_assert_f64_eq {
308    use crate::assert_f64::EQ;
309    use std::panic;
310
311    #[test]
312    fn eq() {
313        let a: f64 = EQ;
314        let b: f64 = EQ;
315        for _ in 0..1 {
316            let actual = assert_f64_eq!(a, b);
317            assert_eq!(actual, ());
318        }
319    }
320}
321
322/// Assert a floating point 64-bit number is equal to another within f64::EPSILON.
323///
324/// Pseudocode:<br>
325/// a = b
326///
327/// This macro provides the same statements as [`assert_f64_eq`](macro.assert_f64_eq.html),
328/// except this macro's statements are only enabled in non-optimized
329/// builds by default. An optimized build will not execute this macro's
330/// statements unless `-C debug-assertions` is passed to the compiler.
331///
332/// This macro is useful for checks that are too expensive to be present
333/// in a release build but may be helpful during development.
334///
335/// The result of expanding this macro is always type checked.
336///
337/// An unchecked assertion allows a program in an inconsistent state to
338/// keep running, which might have unexpected consequences but does not
339/// introduce unsafety as long as this only happens in safe code. The
340/// performance cost of assertions, however, is not measurable in general.
341/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
342/// after thorough profiling, and more importantly, only in safe code!
343///
344/// This macro is intended to work in a similar way to
345/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
346///
347/// # Module macros
348///
349/// * [`assert_f64_eq`](macro@crate::assert_f64_eq)
350/// * [`assert_f64_eq`](macro@crate::assert_f64_eq)
351/// * [`debug_assert_f64_eq`](macro@crate::debug_assert_f64_eq)
352///
353#[macro_export]
354macro_rules! debug_assert_f64_eq {
355    ($($arg:tt)*) => {
356        if $crate::cfg!(debug_assertions) {
357            $crate::assert_f64_eq!($($arg)*);
358        }
359    };
360}