assertables/assert_in/
assert_in_range.rs

1//! Assert an item is in a range.
2//!
3//! Pseudocode:<br>
4//! a is in range
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//!
11//! let a = 1;
12//! let b = 0..2;
13//! assert_in_range!(a, b);
14//! ```
15//!
16//! # Module macros
17//!
18//! * [`assert_in_range`](macro@crate::assert_in_range)
19//! * [`assert_in_range_as_result`](macro@crate::assert_in_range_as_result)
20//! * [`debug_assert_in_range`](macro@crate::debug_assert_in_range)
21
22/// Assert an item is in a range.
23///
24/// Pseudocode:<br>
25/// a is in range
26///
27/// * If true, return Result `Ok(())`.
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_in_range`](macro@crate::assert_in_range)
37/// * [`assert_in_range_as_result`](macro@crate::assert_in_range_as_result)
38/// * [`debug_assert_in_range`](macro@crate::debug_assert_in_range)
39///
40#[macro_export]
41macro_rules! assert_in_range_as_result {
42    ($a:expr, $range:expr $(,)?) => {
43        match (&$a, &$range) {
44            (a, range) => {
45                if range.contains(a) {
46                    Ok(())
47                } else {
48                    Err(format!(
49                        concat!(
50                            "assertion failed: `assert_in_range!(a, range)`\n",
51                            "https://docs.rs/assertables/9.8.1/assertables/macro.assert_in_range.html\n",
52                            "     a label: `{}`,\n",
53                            "     a debug: `{:?}`,\n",
54                            " range label: `{}`,\n",
55                            " range debug: `{:?}`"
56                        ),
57                        stringify!($a),
58                        a,
59                        stringify!($range),
60                        range
61                    ))
62                }
63            }
64        }
65    };
66}
67
68#[cfg(test)]
69mod test_assert_in_range_as_result {
70    use std::sync::Once;
71
72    #[test]
73    fn success_with_range_a_dot_dot_b() {
74        let a: i8 = 1;
75        let b: std::ops::Range<i8> = 0..2;
76        for _ in 0..1 {
77            let actual = assert_in_range_as_result!(a, b);
78            assert_eq!(actual.unwrap(), ());
79        }
80    }
81
82    #[test]
83    fn success_with_range_a_dot_dot_b_once() {
84        static A: Once = Once::new();
85        fn a() -> i8 {
86            if A.is_completed() {
87                panic!("A.is_completed()")
88            } else {
89                A.call_once(|| {})
90            }
91            1
92        }
93
94        static B: Once = Once::new();
95        fn b() -> std::ops::Range<i8> {
96            if B.is_completed() {
97                panic!("B.is_completed()")
98            } else {
99                B.call_once(|| {})
100            }
101            0..2
102        }
103
104        assert_eq!(A.is_completed(), false);
105        assert_eq!(B.is_completed(), false);
106        let result = assert_in_range_as_result!(a(), b());
107        assert!(result.is_ok());
108        assert_eq!(A.is_completed(), true);
109        assert_eq!(B.is_completed(), true);
110    }
111
112    #[test]
113    fn success_with_range_a_dot_dot_eq_b() {
114        let a: i8 = 1;
115        let b: std::ops::RangeInclusive<i8> = 0..=2;
116        for _ in 0..1 {
117            let actual = assert_in_range_as_result!(a, b);
118            assert_eq!(actual.unwrap(), ());
119        }
120    }
121
122    #[test]
123    fn success_with_range_a_dot_dot_eq_b_once() {
124        static A: Once = Once::new();
125        fn a() -> i8 {
126            if A.is_completed() {
127                panic!("A.is_completed()")
128            } else {
129                A.call_once(|| {})
130            }
131            1
132        }
133
134        static B: Once = Once::new();
135        fn b() -> std::ops::RangeInclusive<i8> {
136            if B.is_completed() {
137                panic!("B.is_completed()")
138            } else {
139                B.call_once(|| {})
140            }
141            0..=2
142        }
143
144        assert_eq!(A.is_completed(), false);
145        assert_eq!(B.is_completed(), false);
146        let result = assert_in_range_as_result!(a(), b());
147        assert!(result.is_ok());
148        assert_eq!(A.is_completed(), true);
149        assert_eq!(B.is_completed(), true);
150    }
151
152    #[test]
153    fn failure() {
154        let a: i8 = 1;
155        let b: std::ops::Range<i8> = 2..4;
156        let actual = assert_in_range_as_result!(a, b);
157        let message = concat!(
158            "assertion failed: `assert_in_range!(a, range)`\n",
159            "https://docs.rs/assertables/9.8.1/assertables/macro.assert_in_range.html\n",
160            "     a label: `a`,\n",
161            "     a debug: `1`,\n",
162            " range label: `b`,\n",
163            " range debug: `2..4`"
164        );
165        assert_eq!(actual.unwrap_err(), message);
166    }
167}
168
169/// Assert an item is in a range.
170///
171/// Pseudocode:<br>
172/// a is in range
173///
174/// * If true, return `()`.
175///
176/// * Otherwise, call [`panic!`] with a message and the values of the
177///   expressions with their debug representations.
178///
179/// # Examples
180///
181/// ```rust
182/// use assertables::*;
183/// # use std::panic;
184///
185/// # fn main() {
186/// let a = 1;
187/// let b = 0..2;
188/// assert_in_range!(a, b);
189///
190/// # let result = panic::catch_unwind(|| {
191/// // This will panic
192/// let a = 1;
193/// let b = 2..4;
194/// assert_in_range!(a, b);
195/// # });
196/// // assertion failed: `assert_in_range!(a, range)`
197/// // https://docs.rs/assertables/…/assertables/macro.assert_in_range.html
198/// //  a label: `a`,
199/// //  a debug: `1`,
200/// //  range label: `b`,
201/// //  range debug: `2..4`
202/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
203/// # let message = concat!(
204/// #     "assertion failed: `assert_in_range!(a, range)`\n",
205/// #     "https://docs.rs/assertables/9.8.1/assertables/macro.assert_in_range.html\n",
206/// #     "     a label: `a`,\n",
207/// #     "     a debug: `1`,\n",
208/// #     " range label: `b`,\n",
209/// #     " range debug: `2..4`"
210/// # );
211/// # assert_eq!(actual, message);
212/// # }
213/// ```
214///
215/// # Module macros
216///
217/// * [`assert_in_range`](macro@crate::assert_in_range)
218/// * [`assert_in_range_as_result`](macro@crate::assert_in_range_as_result)
219/// * [`debug_assert_in_range`](macro@crate::debug_assert_in_range)
220///
221#[macro_export]
222macro_rules! assert_in_range {
223    ($a:expr, $range:expr $(,)?) => {
224        match $crate::assert_in_range_as_result!($a, $range) {
225            Ok(()) => (),
226            Err(err) => panic!("{}", err),
227        }
228    };
229    ($a:expr, $range:expr, $($message:tt)+) => {
230        match $crate::assert_in_range_as_result!($a, $range) {
231            Ok(()) => (),
232            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
233        }
234    };
235}
236
237#[cfg(test)]
238mod test_assert_in_range {
239    use std::panic;
240
241    #[test]
242    fn success_with_range_a_dot_dot_b() {
243        let a = 1;
244        let b = 0..2;
245        for _ in 0..1 {
246            let actual = assert_in_range!(a, b);
247            assert_eq!(actual, ());
248        }
249    }
250
251    #[test]
252    fn success_with_range_a_dot_dot_eq_b() {
253        let a = 1;
254        let b = 0..=2;
255        for _ in 0..1 {
256            let actual = assert_in_range!(a, b);
257            assert_eq!(actual, ());
258        }
259    }
260
261    #[test]
262    fn failure() {
263        let a = 1;
264        let b = 2..4;
265        let result = panic::catch_unwind(|| {
266            let _actual = assert_in_range!(a, b);
267        });
268        let message = concat!(
269            "assertion failed: `assert_in_range!(a, range)`\n",
270            "https://docs.rs/assertables/9.8.1/assertables/macro.assert_in_range.html\n",
271            "     a label: `a`,\n",
272            "     a debug: `1`,\n",
273            " range label: `b`,\n",
274            " range debug: `2..4`",
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 an item is in a range.
288///
289/// Pseudocode:<br>
290/// a is in range
291///
292/// This macro provides the same statements as [`assert_in_range`](macro.assert_in_range.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_in_range`](macro@crate::assert_in_range)
315/// * [`assert_in_range`](macro@crate::assert_in_range)
316/// * [`debug_assert_in_range`](macro@crate::debug_assert_in_range)
317///
318#[macro_export]
319macro_rules! debug_assert_in_range {
320    ($($arg:tt)*) => {
321        if $crate::cfg!(debug_assertions) {
322            $crate::assert_in_range!($($arg)*);
323        }
324    };
325}