assertables/assert_count/
assert_count_ge_x.rs

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