Skip to main content

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