assertables/
assert_le.rs

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