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