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(format!(
51                        concat!(
52                            "assertion failed: `assert_count_lt!(a, b)`\n",
53                            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_count_lt.html\n",
54                            " a label: `{}`,\n",
55                            " a debug: `{:?}`,\n",
56                            " a.count(): `{:?}`,\n",
57                            " b label: `{}`,\n",
58                            " b debug: `{:?}`\n",
59                            " b.count(): `{:?}`",
60                        ),
61                        stringify!($a),
62                        a,
63                        a_count,
64                        stringify!($b),
65                        b,
66                        b_count
67                    ))
68                }
69            }
70        }
71    };
72}
73
74#[cfg(test)]
75mod test_assert_count_lt_as_result {
76    use std::sync::Once;
77
78    #[test]
79    fn lt() {
80        let a = "x".chars();
81        let b = "xx".chars();
82        for _ in 0..1 {
83            let actual = assert_count_lt_as_result!(a, b);
84            assert_eq!(actual.unwrap(), (1, 2));
85        }
86    }
87
88    #[test]
89    fn lt_once() {
90        static A: Once = Once::new();
91        fn a() -> std::str::Chars<'static> {
92            if A.is_completed() {
93                panic!("A.is_completed()")
94            } else {
95                A.call_once(|| {})
96            }
97            "x".chars()
98        }
99
100        static B: Once = Once::new();
101        fn b() -> std::str::Chars<'static> {
102            if B.is_completed() {
103                panic!("B.is_completed()")
104            } else {
105                B.call_once(|| {})
106            }
107            "xx".chars()
108        }
109
110        assert_eq!(A.is_completed(), false);
111        assert_eq!(B.is_completed(), false);
112        let result = assert_count_lt_as_result!(a(), b());
113        assert!(result.is_ok());
114        assert_eq!(A.is_completed(), true);
115        assert_eq!(B.is_completed(), true);
116    }
117
118    #[test]
119    fn eq() {
120        let a = "x".chars();
121        let b = "x".chars();
122        let actual = assert_count_lt_as_result!(a, b);
123        let message = concat!(
124            "assertion failed: `assert_count_lt!(a, b)`\n",
125            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_count_lt.html\n",
126            " a label: `a`,\n",
127            " a debug: `Chars(['x'])`,\n",
128            " a.count(): `1`,\n",
129            " b label: `b`,\n",
130            " b debug: `Chars(['x'])`\n",
131            " b.count(): `1`"
132        );
133        assert_eq!(actual.unwrap_err(), message);
134    }
135
136    #[test]
137    fn gt() {
138        let a = "xx".chars();
139        let b = "x".chars();
140        let actual = assert_count_lt_as_result!(a, b);
141        let message = concat!(
142            "assertion failed: `assert_count_lt!(a, b)`\n",
143            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_count_lt.html\n",
144            " a label: `a`,\n",
145            " a debug: `Chars(['x', 'x'])`,\n",
146            " a.count(): `2`,\n",
147            " b label: `b`,\n",
148            " b debug: `Chars(['x'])`\n",
149            " b.count(): `1`"
150        );
151        assert_eq!(actual.unwrap_err(), message);
152    }
153}
154
155/// Assert a count is less than another.
156///
157/// Pseudocode:<br>
158/// a.count() < b.count()
159///
160/// * If true, return `(a.count(), b)`.
161///
162/// * Otherwise, call [`panic!`] with a message and the values of the
163///   expressions with their debug representations.
164///
165/// # Examples
166///
167/// ```rust
168/// use assertables::*;
169/// # use std::panic;
170///
171/// # fn main() {
172/// let a = "x".chars();
173/// let b = "xx".chars();
174/// assert_count_lt!(a, b);
175///
176/// # let result = panic::catch_unwind(|| {
177/// // This will panic
178/// let a = "xx".chars();
179/// let b = "x".chars();
180/// assert_count_lt!(a, b);
181/// # });
182/// // assertion failed: `assert_count_lt!(a, b)`
183/// // https://docs.rs/assertables/…/assertables/macro.assert_count_lt.html
184/// //  a label: `a`,
185/// //  a debug: `Chars(['x', 'x'])`,
186/// //  a.count(): `2`",
187/// //  b label: `b`,
188/// //  b debug: `Chars(['x'])`,
189/// //  b.count(): `1`"
190/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
191/// # let message = concat!(
192/// #     "assertion failed: `assert_count_lt!(a, b)`\n",
193/// #     "https://docs.rs/assertables/9.8.2/assertables/macro.assert_count_lt.html\n",
194/// #     " a label: `a`,\n",
195/// #     " a debug: `Chars(['x', 'x'])`,\n",
196/// #     " a.count(): `2`,\n",
197/// #     " b label: `b`,\n",
198/// #     " b debug: `Chars(['x'])`\n",
199/// #     " b.count(): `1`",
200/// # );
201/// # assert_eq!(actual, message);
202/// # }
203/// ```
204///
205/// # Module macros
206///
207/// * [`assert_count_lt`](macro@crate::assert_count_lt)
208/// * [`assert_count_lt_as_result`](macro@crate::assert_count_lt_as_result)
209/// * [`debug_assert_count_lt`](macro@crate::debug_assert_count_lt)
210///
211#[macro_export]
212macro_rules! assert_count_lt {
213    ($a:expr, $b:expr $(,)?) => {
214        match $crate::assert_count_lt_as_result!($a, $b) {
215            Ok(x) => x,
216            Err(err) => panic!("{}", err),
217        }
218    };
219    ($a:expr, $b:expr, $($message:tt)+) => {
220        match $crate::assert_count_lt_as_result!($a, $b) {
221            Ok(x) => x,
222            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
223        }
224    };
225}
226
227#[cfg(test)]
228mod test_assert_count_lt {
229    use std::panic;
230
231    #[test]
232    fn lt() {
233        let a = "x".chars();
234        let b = "xx".chars();
235        for _ in 0..1 {
236            let actual = assert_count_lt!(a, b);
237            assert_eq!(actual, (1, 2));
238        }
239    }
240
241    #[test]
242    fn eq() {
243        let result = panic::catch_unwind(|| {
244            let a = "x".chars();
245            let b = "x".chars();
246            let _actual = assert_count_lt!(a, b);
247        });
248        let message = concat!(
249            "assertion failed: `assert_count_lt!(a, b)`\n",
250            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_count_lt.html\n",
251            " a label: `a`,\n",
252            " a debug: `Chars(['x'])`,\n",
253            " a.count(): `1`,\n",
254            " b label: `b`,\n",
255            " b debug: `Chars(['x'])`\n",
256            " b.count(): `1`"
257        );
258        assert_eq!(
259            result
260                .unwrap_err()
261                .downcast::<String>()
262                .unwrap()
263                .to_string(),
264            message
265        );
266    }
267
268    #[test]
269    fn gt() {
270        let result = panic::catch_unwind(|| {
271            let a = "xx".chars();
272            let b = "x".chars();
273            let _actual = assert_count_lt!(a, b);
274        });
275        let message = concat!(
276            "assertion failed: `assert_count_lt!(a, b)`\n",
277            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_count_lt.html\n",
278            " a label: `a`,\n",
279            " a debug: `Chars(['x', 'x'])`,\n",
280            " a.count(): `2`,\n",
281            " b label: `b`,\n",
282            " b debug: `Chars(['x'])`\n",
283            " b.count(): `1`"
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 less than another.
297///
298/// Pseudocode:<br>
299/// a.count() < b.count()
300///
301/// This macro provides the same statements as [`assert_count_lt`](macro.assert_count_lt.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_lt`](macro@crate::assert_count_lt)
324/// * [`assert_count_lt`](macro@crate::assert_count_lt)
325/// * [`debug_assert_count_lt`](macro@crate::debug_assert_count_lt)
326///
327#[macro_export]
328macro_rules! debug_assert_count_lt {
329    ($($arg:tt)*) => {
330        if $crate::cfg!(debug_assertions) {
331            $crate::assert_count_lt!($($arg)*);
332        }
333    };
334}