assertables/assert_len/
assert_len_ne.rs

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