Skip to main content

assertables/assert_len/
assert_len_lt.rs

1//! Assert a length is less than 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_lt!(a, b);
14//! ```
15//!
16//! # Module macros
17//!
18//! * [`assert_len_lt`](macro@crate::assert_len_lt)
19//! * [`assert_len_lt_as_result`](macro@crate::assert_len_lt_as_result)
20//! * [`debug_assert_len_lt`](macro@crate::debug_assert_len_lt)
21
22/// Assert a length is less than 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_lt`](macro@crate::assert_len_lt)
37/// * [`assert_len_lt_as_result`](macro@crate::assert_len_lt_as_result)
38/// * [`debug_assert_len_lt`](macro@crate::debug_assert_len_lt)
39///
40#[macro_export]
41macro_rules! assert_len_lt_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_lt!(a, b)`\n",
53                            "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.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_lt_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_lt_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_lt_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 eq() {
120        let a = "x";
121        let b = "x";
122        let actual = assert_len_lt_as_result!(a, b);
123        let message = concat!(
124            "assertion failed: `assert_len_lt!(a, b)`\n",
125            "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.html\n",
126            " a label: `a`,\n",
127            " a debug: `\"x\"`,\n",
128            " a.len(): `1`,\n",
129            " b label: `b`,\n",
130            " b debug: `\"x\"`\n",
131            " b.len(): `1`"
132        );
133        assert_eq!(actual.unwrap_err(), message);
134    }
135
136    #[test]
137    fn gt() {
138        let a = "xx";
139        let b = "x";
140        let actual = assert_len_lt_as_result!(a, b);
141        let message = concat!(
142            "assertion failed: `assert_len_lt!(a, b)`\n",
143            "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.html\n",
144            " a label: `a`,\n",
145            " a debug: `\"xx\"`,\n",
146            " a.len(): `2`,\n",
147            " b label: `b`,\n",
148            " b debug: `\"x\"`\n",
149            " b.len(): `1`"
150        );
151        assert_eq!(actual.unwrap_err(), message);
152    }
153}
154
155/// Assert a length is less than another.
156///
157/// Pseudocode:<br>
158/// a.len() < b.len()
159///
160/// * If true, return `(a.len(), b.len())`.
161///
162/// * Otherwise, call [`panic!`] with a message and the values of the
163///   expressions with their debug representations.
164///
165/// # Examples
166///
167/// ```rust
168/// use assertables::*;
169/// # use std::panic;
170///
171/// # fn main() {
172/// let a = "x";
173/// let b = "xx";
174/// assert_len_lt!(a, b);
175///
176/// # let result = panic::catch_unwind(|| {
177/// // This will panic
178/// let a = "xx";
179/// let b = "x";
180/// assert_len_lt!(a, b);
181/// # });
182/// // assertion failed: `assert_len_lt!(a, b)`
183/// // https://docs.rs/assertables/…/assertables/macro.assert_len_lt.html
184/// //  a label: `a`,
185/// //  a debug: `\"xx\"`,
186/// //  a.len(): `2`",
187/// //  b label: `b`,
188/// //  b debug: `\"x\"`,
189/// //  b.len(): `1`"
190/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
191/// # let message = concat!(
192/// #     "assertion failed: `assert_len_lt!(a, b)`\n",
193/// #     "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.html\n",
194/// #     " a label: `a`,\n",
195/// #     " a debug: `\"xx\"`,\n",
196/// #     " a.len(): `2`,\n",
197/// #     " b label: `b`,\n",
198/// #     " b debug: `\"x\"`\n",
199/// #     " b.len(): `1`",
200/// # );
201/// # assert_eq!(actual, message);
202/// # }
203/// ```
204///
205/// # Module macros
206///
207/// * [`assert_len_lt`](macro@crate::assert_len_lt)
208/// * [`assert_len_lt_as_result`](macro@crate::assert_len_lt_as_result)
209/// * [`debug_assert_len_lt`](macro@crate::debug_assert_len_lt)
210///
211#[macro_export]
212macro_rules! assert_len_lt {
213    ($a:expr, $b:expr $(,)?) => {
214        match $crate::assert_len_lt_as_result!($a, $b) {
215            Ok(x) => x,
216            Err(err) => panic!("{}", err),
217        }
218    };
219    ($a:expr, $b:expr, $($message:tt)+) => {
220        match $crate::assert_len_lt_as_result!($a, $b) {
221            Ok(x) => x,
222            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
223        }
224    };
225}
226
227#[cfg(test)]
228mod test_assert_len_lt {
229    use std::panic;
230
231    #[test]
232    fn lt() {
233        let a = "x";
234        let b = "xx";
235        for _ in 0..1 {
236            let actual = assert_len_lt!(a, b);
237            assert_eq!(actual, (1, 2));
238        }
239    }
240
241    #[test]
242    fn eq() {
243        let a = "x";
244        let b = "x";
245        let result = panic::catch_unwind(|| {
246            let _actual = assert_len_lt!(a, b);
247        });
248        let message = concat!(
249            "assertion failed: `assert_len_lt!(a, b)`\n",
250            "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.html\n",
251            " a label: `a`,\n",
252            " a debug: `\"x\"`,\n",
253            " a.len(): `1`,\n",
254            " b label: `b`,\n",
255            " b debug: `\"x\"`\n",
256            " b.len(): `1`"
257        );
258        assert_eq!(
259            result
260                .unwrap_err()
261                .downcast::<String>()
262                .unwrap()
263                .to_string(),
264            message
265        );
266    }
267
268    #[test]
269    fn gt() {
270        let a = "xx";
271        let b = "x";
272        let result = panic::catch_unwind(|| {
273            let _actual = assert_len_lt!(a, b);
274        });
275        let message = concat!(
276            "assertion failed: `assert_len_lt!(a, b)`\n",
277            "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.html\n",
278            " a label: `a`,\n",
279            " a debug: `\"xx\"`,\n",
280            " a.len(): `2`,\n",
281            " b label: `b`,\n",
282            " b debug: `\"x\"`\n",
283            " b.len(): `1`"
284        );
285        assert_eq!(
286            result
287                .unwrap_err()
288                .downcast::<String>()
289                .unwrap()
290                .to_string(),
291            message
292        );
293    }
294}
295
296/// Assert a length is less than another.
297///
298/// Pseudocode:<br>
299/// a.len() < b.len()
300///
301/// This macro provides the same statements as [`assert_len_lt`](macro.assert_len_lt.html),
302/// except this macro's statements are only enabled in non-optimized
303/// builds by default. An optimized build will not execute this macro's
304/// statements unless `-C debug-assertions` is passed to the compiler.
305///
306/// This macro is useful for checks that are too expensive to be present
307/// in a release build but may be helpful during development.
308///
309/// The result of expanding this macro is always type checked.
310///
311/// An unchecked assertion allows a program in an inconsistent state to
312/// keep running, which might have unexpected consequences but does not
313/// introduce unsafety as long as this only happens in safe code. The
314/// performance cost of assertions, however, is not measurable in general.
315/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
316/// after thorough profiling, and more importantly, only in safe code!
317///
318/// This macro is intended to work in a similar way to
319/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
320///
321/// # Module macros
322///
323/// * [`assert_len_lt`](macro@crate::assert_len_lt)
324/// * [`assert_len_lt`](macro@crate::assert_len_lt)
325/// * [`debug_assert_len_lt`](macro@crate::debug_assert_len_lt)
326///
327#[macro_export]
328macro_rules! debug_assert_len_lt {
329    ($($arg:tt)*) => {
330        if cfg!(debug_assertions) {
331            $crate::assert_len_lt!($($arg)*);
332        }
333    };
334}
335
336#[cfg(test)]
337mod test_debug_assert_len_lt {
338    use std::panic;
339
340    #[test]
341    fn lt() {
342        let a = "x";
343        let b = "xx";
344        for _ in 0..1 {
345            let _actual = debug_assert_len_lt!(a, b);
346            // assert_eq!(actual, (1, 2));
347        }
348    }
349
350    #[test]
351    fn eq() {
352        let a = "x";
353        let b = "x";
354        let result = panic::catch_unwind(|| {
355            let _actual = debug_assert_len_lt!(a, b);
356        });
357        let message = concat!(
358            "assertion failed: `assert_len_lt!(a, b)`\n",
359            "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.html\n",
360            " a label: `a`,\n",
361            " a debug: `\"x\"`,\n",
362            " a.len(): `1`,\n",
363            " b label: `b`,\n",
364            " b debug: `\"x\"`\n",
365            " b.len(): `1`"
366        );
367        assert_eq!(
368            result
369                .unwrap_err()
370                .downcast::<String>()
371                .unwrap()
372                .to_string(),
373            message
374        );
375    }
376
377    #[test]
378    fn gt() {
379        let a = "xx";
380        let b = "x";
381        let result = panic::catch_unwind(|| {
382            let _actual = debug_assert_len_lt!(a, b);
383        });
384        let message = concat!(
385            "assertion failed: `assert_len_lt!(a, b)`\n",
386            "https://docs.rs/assertables/9.8.6/assertables/macro.assert_len_lt.html\n",
387            " a label: `a`,\n",
388            " a debug: `\"xx\"`,\n",
389            " a.len(): `2`,\n",
390            " b label: `b`,\n",
391            " b debug: `\"x\"`\n",
392            " b.len(): `1`"
393        );
394        assert_eq!(
395            result
396                .unwrap_err()
397                .downcast::<String>()
398                .unwrap()
399                .to_string(),
400            message
401        );
402    }
403}