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