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