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.5.4/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
71    #[test]
72    fn success_with_range_a_dot_dot_b() {
73        let a: i8 = 1;
74        let b: std::ops::Range<i8> = 0..2;
75        let actual = assert_in_range_as_result!(a, b);
76        assert_eq!(actual.unwrap(), ());
77    }
78
79    #[test]
80    fn success_with_range_a_dot_dot_eq_b() {
81        let a: i8 = 1;
82        let b: std::ops::RangeInclusive<i8> = 0..=2;
83        let actual = assert_in_range_as_result!(a, b);
84        assert_eq!(actual.unwrap(), ());
85    }
86
87    #[test]
88    fn failure() {
89        let a: i8 = 1;
90        let b: std::ops::Range<i8> = 2..4;
91        let actual = assert_in_range_as_result!(a, b);
92        let message = concat!(
93            "assertion failed: `assert_in_range!(a, range)`\n",
94            "https://docs.rs/assertables/9.5.4/assertables/macro.assert_in_range.html\n",
95            "     a label: `a`,\n",
96            "     a debug: `1`,\n",
97            " range label: `b`,\n",
98            " range debug: `2..4`"
99        );
100        assert_eq!(actual.unwrap_err(), message);
101    }
102
103    use std::sync::Once;
104    #[test]
105    fn once() {
106
107        static A: Once = Once::new();
108        fn a() -> i8 {
109            if A.is_completed() { panic!("A.is_completed()") } else { A.call_once(|| {}) }
110            1
111        }
112
113        static B: Once = Once::new();
114        fn b() -> std::ops::Range<i8> {
115            if B.is_completed() { panic!("B.is_completed()") } else { B.call_once(|| {}) }
116             0..2
117        }
118
119        assert_eq!(A.is_completed(), false);
120        assert_eq!(B.is_completed(), false);
121        let result = assert_in_range_as_result!(a(), b());
122        assert!(result.is_ok());
123        assert_eq!(A.is_completed(), true);
124        assert_eq!(B.is_completed(), true);
125    }
126
127}
128
129/// Assert an item is in a range.
130///
131/// Pseudocode:<br>
132/// a is in range
133///
134/// * If true, return `()`.
135///
136/// * Otherwise, call [`panic!`] with a message and the values of the
137///   expressions with their debug representations.
138///
139/// # Examples
140///
141/// ```rust
142/// use assertables::*;
143/// # use std::panic;
144///
145/// # fn main() {
146/// let a = 1;
147/// let b = 0..2;
148/// assert_in_range!(a, b);
149///
150/// # let result = panic::catch_unwind(|| {
151/// // This will panic
152/// let a = 1;
153/// let b = 2..4;
154/// assert_in_range!(a, b);
155/// # });
156/// // assertion failed: `assert_in_range!(a, range)`
157/// // https://docs.rs/assertables/9.5.4/assertables/macro.assert_in_range.html
158/// //  a label: `a`,
159/// //  a debug: `1`,
160/// //  range label: `b`,
161/// //  range debug: `2..4`
162/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
163/// # let message = concat!(
164/// #     "assertion failed: `assert_in_range!(a, range)`\n",
165/// #     "https://docs.rs/assertables/9.5.4/assertables/macro.assert_in_range.html\n",
166/// #     "     a label: `a`,\n",
167/// #     "     a debug: `1`,\n",
168/// #     " range label: `b`,\n",
169/// #     " range debug: `2..4`"
170/// # );
171/// # assert_eq!(actual, message);
172/// # }
173/// ```
174///
175/// # Module macros
176///
177/// * [`assert_in_range`](macro@crate::assert_in_range)
178/// * [`assert_in_range_as_result`](macro@crate::assert_in_range_as_result)
179/// * [`debug_assert_in_range`](macro@crate::debug_assert_in_range)
180///
181#[macro_export]
182macro_rules! assert_in_range {
183    ($a:expr, $range:expr $(,)?) => {{
184        match $crate::assert_in_range_as_result!($a, $range) {
185            Ok(()) => (),
186            Err(err) => panic!("{}", err),
187        }
188    }};
189    ($a:expr, $range:expr, $($message:tt)+) => {{
190        match $crate::assert_in_range_as_result!($a, $range) {
191            Ok(()) => (),
192            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
193        }
194    }};
195}
196
197#[cfg(test)]
198mod test_assert_in_range {
199    use std::panic;
200
201    #[test]
202    fn success_with_range_a_dot_dot_b() {
203        let a = 1;
204        let b = 0..2;
205        let actual = assert_in_range!(a, b);
206        assert_eq!(actual, ());
207    }
208
209    #[test]
210    fn success_with_range_a_dot_dot_eq_b() {
211        let a = 1;
212        let b = 0..=2;
213        let actual = assert_in_range!(a, b);
214        assert_eq!(actual, ());
215    }
216
217    #[test]
218    fn failure() {
219        let a = 1;
220        let b = 2..4;
221        let result = panic::catch_unwind(|| {
222            let _actual = assert_in_range!(a, b);
223        });
224        let message = concat!(
225            "assertion failed: `assert_in_range!(a, range)`\n",
226            "https://docs.rs/assertables/9.5.4/assertables/macro.assert_in_range.html\n",
227            "     a label: `a`,\n",
228            "     a debug: `1`,\n",
229            " range label: `b`,\n",
230            " range debug: `2..4`",
231        );
232        assert_eq!(
233            result
234                .unwrap_err()
235                .downcast::<String>()
236                .unwrap()
237                .to_string(),
238            message
239        );
240    }
241}
242
243/// Assert an item is in a range.
244///
245/// Pseudocode:<br>
246/// a is in range
247///
248/// This macro provides the same statements as [`assert_in_range`](macro.assert_in_range.html),
249/// except this macro's statements are only enabled in non-optimized
250/// builds by default. An optimized build will not execute this macro's
251/// statements unless `-C debug-assertions` is passed to the compiler.
252///
253/// This macro is useful for checks that are too expensive to be present
254/// in a release build but may be helpful during development.
255///
256/// The result of expanding this macro is always type checked.
257///
258/// An unchecked assertion allows a program in an inconsistent state to
259/// keep running, which might have unexpected consequences but does not
260/// introduce unsafety as long as this only happens in safe code. The
261/// performance cost of assertions, however, is not measurable in general.
262/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
263/// after thorough profiling, and more importantly, only in safe code!
264///
265/// This macro is intended to work in a similar way to
266/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
267///
268/// # Module macros
269///
270/// * [`assert_in_range`](macro@crate::assert_in_range)
271/// * [`assert_in_range`](macro@crate::assert_in_range)
272/// * [`debug_assert_in_range`](macro@crate::debug_assert_in_range)
273///
274#[macro_export]
275macro_rules! debug_assert_in_range {
276    ($($arg:tt)*) => {
277        if $crate::cfg!(debug_assertions) {
278            $crate::assert_in_range!($($arg)*);
279        }
280    };
281}