Skip to main content

assertables/assert_fn_ok/
assert_fn_ok_le_x.rs

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