Skip to main content

assertables/assert_abs_diff/
assert_abs_diff_gt_x.rs

1//! Assert an absolute difference is greater than an expression.
2//!
3//! Pseudocode:<br>
4//! |Δ| > x
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//!
11//! let a = 10;
12//! let b = 13;
13//! let x = 2;
14//! assert_abs_diff_gt_x!(a, b, x);
15//! ```
16//!
17//! # Module macros
18//!
19//! * [`assert_abs_diff_gt_x`](macro@crate::assert_abs_diff_gt_x)
20//! * [`assert_abs_diff_gt_x_as_result`](macro@crate::assert_abs_diff_gt_x_as_result)
21//! * [`debug_assert_abs_diff_gt_x`](macro@crate::debug_assert_abs_diff_gt_x)
22
23/// Assert an absolute difference is greater than an expression.
24///
25/// Pseudocode:<br>
26/// |Δ| > x
27///
28/// * If true, return `Ok((lhs, rhs))`.
29///
30/// * Otherwise, return [`Err`] with a message and the values of the
31///   expressions with their debug representations.
32///
33/// This macro is useful for runtime checks, such as checking parameters,
34/// or sanitizing inputs, or handling different results in different ways.
35///
36/// # Module macros
37///
38/// * [`assert_abs_diff_gt_x`](macro@crate::assert_abs_diff_gt_x)
39/// * [`assert_abs_diff_gt_x_as_result`](macro@crate::assert_abs_diff_gt_x_as_result)
40/// * [`debug_assert_abs_diff_gt_x`](macro@crate::debug_assert_abs_diff_gt_x)
41///
42#[macro_export]
43macro_rules! assert_abs_diff_gt_x_as_result {
44    ($a:expr, $b:expr, $x:expr $(,)?) => {
45        match (&$a, &$b, &$x) {
46            (a, b, x) => {
47                match ::std::panic::catch_unwind(|| if (a >= b) { a - b } else { b - a }) {
48                    Ok(abs_diff) => {
49                        if abs_diff > *x {
50                            Ok((abs_diff, *x))
51                        } else {
52                            Err(format!(
53                                concat!(
54                                    "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
55                                    "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
56                                    " a label: `{}`,\n",
57                                    " a debug: `{:?}`,\n",
58                                    " b label: `{}`,\n",
59                                    " b debug: `{:?}`,\n",
60                                    " x label: `{}`,\n",
61                                    " x debug: `{:?}`,\n",
62                                    "     |Δ|: `{:?}`,\n",
63                                    " |Δ| > x: {}"
64                                ),
65                                stringify!($a),
66                                a,
67                                stringify!($b),
68                                b,
69                                stringify!($x),
70                                x,
71                                abs_diff,
72                                false
73                            ))
74                        }
75                    }
76                    Err(_err) => {
77                        Err(format!(
78                            concat!(
79                                "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
80                                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
81                                " a label: `{}`,\n",
82                                " a debug: `{:?}`,\n",
83                                " b label: `{}`,\n",
84                                " b debug: `{:?}`,\n",
85                                " x label: `{}`,\n",
86                                " x debug: `{:?}`,\n",
87                                "     |Δ|: panic", //TODO add the panic message
88                            ),
89                            stringify!($a),
90                            a,
91                            stringify!($b),
92                            b,
93                            stringify!($x),
94                            x
95                        ))
96                    }
97                }
98            }
99        }
100    };
101}
102
103#[cfg(test)]
104mod test_assert_abs_diff_gt_x_as_result {
105    use std::sync::Once;
106
107    #[test]
108    fn gt() {
109        let a: i8 = 10;
110        let b: i8 = 13;
111        let x: i8 = 2;
112        for _ in 0..1 {
113            let actual = assert_abs_diff_gt_x_as_result!(a, b, x);
114            let expect = (3, 2);
115            assert_eq!(actual.unwrap(), expect);
116        }
117    }
118
119    #[test]
120    fn gt_once() {
121        static A: Once = Once::new();
122        fn a() -> i8 {
123            if A.is_completed() {
124                panic!("A.is_completed()")
125            } else {
126                A.call_once(|| {})
127            }
128            10
129        }
130
131        static B: Once = Once::new();
132        fn b() -> i8 {
133            if B.is_completed() {
134                panic!("B.is_completed()")
135            } else {
136                B.call_once(|| {})
137            }
138            13
139        }
140
141        static X: Once = Once::new();
142        fn x() -> i8 {
143            if X.is_completed() {
144                panic!("X.is_completed()")
145            } else {
146                X.call_once(|| {})
147            }
148            2
149        }
150
151        assert_eq!(A.is_completed(), false);
152        assert_eq!(B.is_completed(), false);
153        assert_eq!(X.is_completed(), false);
154        let result = assert_abs_diff_gt_x_as_result!(a(), b(), x());
155        assert!(result.is_ok());
156        assert_eq!(A.is_completed(), true);
157        assert_eq!(B.is_completed(), true);
158        assert_eq!(X.is_completed(), true);
159    }
160
161    #[test]
162    fn eq() {
163        let a: i8 = 10;
164        let b: i8 = 13;
165        let x: i8 = 3;
166        let actual = assert_abs_diff_gt_x_as_result!(a, b, x);
167        let message = concat!(
168            "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
169            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
170            " a label: `a`,\n",
171            " a debug: `10`,\n",
172            " b label: `b`,\n",
173            " b debug: `13`,\n",
174            " x label: `x`,\n",
175            " x debug: `3`,\n",
176            "     |Δ|: `3`,\n",
177            " |Δ| > x: false"
178        );
179        assert_eq!(actual.unwrap_err(), message);
180    }
181
182    #[test]
183    fn lt() {
184        let a: i8 = 10;
185        let b: i8 = 13;
186        let x: i8 = 4;
187        let actual = assert_abs_diff_gt_x_as_result!(a, b, x);
188        let message = concat!(
189            "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
190            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
191            " a label: `a`,\n",
192            " a debug: `10`,\n",
193            " b label: `b`,\n",
194            " b debug: `13`,\n",
195            " x label: `x`,\n",
196            " x debug: `4`,\n",
197            "     |Δ|: `3`,\n",
198            " |Δ| > x: false"
199        );
200        assert_eq!(actual.unwrap_err(), message);
201    }
202
203    #[test]
204    fn overflow() {
205        let a: i8 = i8::MAX;
206        let b: i8 = i8::MIN;
207        let x: i8 = 0;
208        let actual = assert_abs_diff_gt_x_as_result!(a, b, x);
209        let message = format!(
210            concat!(
211                "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
212                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
213                " a label: `a`,\n",
214                " a debug: `{}`,\n",
215                " b label: `b`,\n",
216                " b debug: `{}`,\n",
217                " x label: `x`,\n",
218                " x debug: `{}`,\n",
219                "     |Δ|: panic"
220            ),
221            a, b, x
222        );
223        assert_eq!(actual.unwrap_err(), message);
224    }
225}
226
227/// Assert an absolute difference is greater than an expression.
228///
229/// Pseudocode:<br>
230/// |Δ| > x
231///
232/// * If true, return `(lhs, rhs)`.
233///
234/// * Otherwise, call [`panic!`] with a message and the values of the
235///   expressions with their debug representations.
236///
237/// # Examples
238///
239/// ```rust
240/// use assertables::*;
241/// # use std::panic;
242///
243/// # fn main() {
244/// let a = 10;
245/// let b = 13;
246/// let x = 2;
247/// assert_abs_diff_gt_x!(a, b, x);
248///
249/// # let result = panic::catch_unwind(|| {
250/// // This will panic
251/// let a = 10;
252/// let b = 13;
253/// let x = 4;
254/// assert_abs_diff_gt_x!(a, b, x);
255/// # });
256/// // assertion failed: `assert_abs_diff_gt_x!(a, b)`
257/// // https://docs.rs/assertables/…/assertables/macro.assert_abs_diff_gt_x.html
258/// //  a label: `a`,
259/// //  a debug: `10`,
260/// //  b label: `b`,
261/// //  b debug: `13`,
262/// //  x label: `x`,
263/// //  x debug: `4`,
264/// //      |Δ|: `3`,
265/// //  |Δ| > x: false
266/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
267/// # let message = concat!(
268/// #     "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
269/// #     "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
270/// #     " a label: `a`,\n",
271/// #     " a debug: `10`,\n",
272/// #     " b label: `b`,\n",
273/// #     " b debug: `13`,\n",
274/// #     " x label: `x`,\n",
275/// #     " x debug: `4`,\n",
276/// #     "     |Δ|: `3`,\n",
277/// #     " |Δ| > x: false"
278/// # );
279/// # assert_eq!(actual, message);
280/// # }
281/// ```
282///
283/// # Module macros
284///
285/// * [`assert_abs_diff_gt_x`](macro@crate::assert_abs_diff_gt_x)
286/// * [`assert_abs_diff_gt_x_as_result`](macro@crate::assert_abs_diff_gt_x_as_result)
287/// * [`debug_assert_abs_diff_gt_x`](macro@crate::debug_assert_abs_diff_gt_x)
288///
289#[macro_export]
290macro_rules! assert_abs_diff_gt_x {
291    ($a:expr, $b:expr, $x:expr $(,)?) => {
292        match $crate::assert_abs_diff_gt_x_as_result!($a, $b, $x) {
293            Ok(x) => x,
294            Err(err) => panic!("{}", err),
295        }
296    };
297    ($a:expr, $b:expr, $x:expr, $($message:tt)+) => {
298        match $crate::assert_abs_diff_gt_x_as_result!($a, $b, $x) {
299            Ok(x) => x,
300            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
301        }
302    };
303}
304
305#[cfg(test)]
306mod test_assert_abs_diff_gt_x {
307    use std::panic;
308
309    #[test]
310    fn gt() {
311        let a = 10;
312        let b = 13;
313        let x = 2;
314        for _ in 0..1 {
315            let actual = assert_abs_diff_gt_x!(a, b, x);
316            let expect = (3, 2);
317            assert_eq!(actual, expect);
318        }
319    }
320
321    #[test]
322    fn eq() {
323        let result = panic::catch_unwind(|| {
324            let a = 10;
325            let b = 13;
326            let x = 3;
327            let _actual = assert_abs_diff_gt_x!(a, b, x);
328        });
329        let message = concat!(
330            "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
331            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
332            " a label: `a`,\n",
333            " a debug: `10`,\n",
334            " b label: `b`,\n",
335            " b debug: `13`,\n",
336            " x label: `x`,\n",
337            " x debug: `3`,\n",
338            "     |Δ|: `3`,\n",
339            " |Δ| > x: false"
340        );
341        assert_eq!(
342            result
343                .unwrap_err()
344                .downcast::<String>()
345                .unwrap()
346                .to_string(),
347            message
348        );
349    }
350
351    #[test]
352    fn lt() {
353        let result = panic::catch_unwind(|| {
354            let a = 10;
355            let b = 13;
356            let x = 4;
357            let _actual = assert_abs_diff_gt_x!(a, b, x);
358        });
359        let message = concat!(
360            "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
361            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
362            " a label: `a`,\n",
363            " a debug: `10`,\n",
364            " b label: `b`,\n",
365            " b debug: `13`,\n",
366            " x label: `x`,\n",
367            " x debug: `4`,\n",
368            "     |Δ|: `3`,\n",
369            " |Δ| > x: false"
370        );
371        assert_eq!(
372            result
373                .unwrap_err()
374                .downcast::<String>()
375                .unwrap()
376                .to_string(),
377            message
378        );
379    }
380
381    #[test]
382    fn overflow() {
383        let a: i8 = i8::MAX;
384        let b: i8 = i8::MIN;
385        let x: i8 = 0;
386        let result = panic::catch_unwind(|| {
387            let _actual = assert_abs_diff_gt_x!(a, b, x);
388        });
389        let message = format!(
390            concat!(
391                "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
392                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
393                " a label: `a`,\n",
394                " a debug: `{}`,\n",
395                " b label: `b`,\n",
396                " b debug: `{}`,\n",
397                " x label: `x`,\n",
398                " x debug: `{}`,\n",
399                "     |Δ|: panic"
400            ),
401            a, b, x
402        );
403        assert_eq!(
404            result
405                .unwrap_err()
406                .downcast::<String>()
407                .unwrap()
408                .to_string(),
409            message
410        );
411    }
412}
413
414/// Assert an absolute difference is greater than an expression.
415///
416/// Pseudocode:<br>
417/// |Δ| > c
418///
419/// This macro provides the same statements as [`assert_abs_diff_gt_x`](macro.assert_abs_diff_gt_x.html),
420/// except this macro's statements are only enabled in non-optimized
421/// builds by default. An optimized build will not execute this macro's
422/// statements unless `-x debug-assertions` is passed to the compiler.
423///
424/// This macro is useful for checks that are too expensive to be present
425/// in a release build but may be helpful during development.
426///
427/// The result of expanding this macro is always type checked.
428///
429/// An unchecked assertion allows a program in an inconsistent state to
430/// keep running, which might have unexpected consequences but does not
431/// introduce unsafety as long as this only happens in safe code. The
432/// performance cost of assertions, however, is not measurable in general.
433/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
434/// after thorough profiling, and more importantly, only in safe code!
435///
436/// This macro is intended to work in a similar way to
437/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
438///
439/// # Module macros
440///
441/// * [`assert_abs_diff_gt_x`](macro@crate::assert_abs_diff_gt_x)
442/// * [`assert_abs_diff_gt_x`](macro@crate::assert_abs_diff_gt_x)
443/// * [`debug_assert_abs_diff_gt_x`](macro@crate::debug_assert_abs_diff_gt_x)
444///
445#[macro_export]
446macro_rules! debug_assert_abs_diff_gt_x {
447    ($($arg:tt)*) => {
448        if cfg!(debug_assertions) {
449            $crate::assert_abs_diff_gt_x!($($arg)*);
450        }
451    };
452}
453
454#[cfg(test)]
455mod test_debug_assert_abs_diff_gt_x {
456    use std::panic;
457
458    #[test]
459    fn gt() {
460        let a = 10;
461        let b = 13;
462        let x = 2;
463        for _ in 0..1 {
464            let _actual = debug_assert_abs_diff_gt_x!(a, b, x);
465            let _expect = (3, 2);
466            // assert_eq!(actual, expect);
467        }
468    }
469
470    #[test]
471    fn eq() {
472        let result = panic::catch_unwind(|| {
473            let a = 10;
474            let b = 13;
475            let x = 3;
476            let _actual = debug_assert_abs_diff_gt_x!(a, b, x);
477        });
478        let message = concat!(
479            "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
480            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
481            " a label: `a`,\n",
482            " a debug: `10`,\n",
483            " b label: `b`,\n",
484            " b debug: `13`,\n",
485            " x label: `x`,\n",
486            " x debug: `3`,\n",
487            "     |Δ|: `3`,\n",
488            " |Δ| > x: false"
489        );
490        assert_eq!(
491            result
492                .unwrap_err()
493                .downcast::<String>()
494                .unwrap()
495                .to_string(),
496            message
497        );
498    }
499
500    #[test]
501    fn lt() {
502        let result = panic::catch_unwind(|| {
503            let a = 10;
504            let b = 13;
505            let x = 4;
506            let _actual = debug_assert_abs_diff_gt_x!(a, b, x);
507        });
508        let message = concat!(
509            "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
510            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
511            " a label: `a`,\n",
512            " a debug: `10`,\n",
513            " b label: `b`,\n",
514            " b debug: `13`,\n",
515            " x label: `x`,\n",
516            " x debug: `4`,\n",
517            "     |Δ|: `3`,\n",
518            " |Δ| > x: false"
519        );
520        assert_eq!(
521            result
522                .unwrap_err()
523                .downcast::<String>()
524                .unwrap()
525                .to_string(),
526            message
527        );
528    }
529
530    #[test]
531    fn overflow() {
532        let a: i8 = i8::MAX;
533        let b: i8 = i8::MIN;
534        let x: i8 = 0;
535        let result = panic::catch_unwind(|| {
536            let _actual = debug_assert_abs_diff_gt_x!(a, b, x);
537        });
538        let message = format!(
539            concat!(
540                "assertion failed: `assert_abs_diff_gt_x!(a, b, x)`\n",
541                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_abs_diff_gt_x.html\n",
542                " a label: `a`,\n",
543                " a debug: `{}`,\n",
544                " b label: `b`,\n",
545                " b debug: `{}`,\n",
546                " x label: `x`,\n",
547                " x debug: `{}`,\n",
548                "     |Δ|: panic"
549            ),
550            a, b, x
551        );
552        assert_eq!(
553            result
554                .unwrap_err()
555                .downcast::<String>()
556                .unwrap()
557                .to_string(),
558            message
559        );
560    }
561}