Skip to main content

assertables/assert_len/
assert_len_gt_x.rs

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