assertables/assert_len/
assert_len_ne_x.rs

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