assertables/assert_count/
assert_count_lt.rs

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