Skip to main content

assertables/assert_any/
assert_any_ne_x.rs

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