assertables/assert_in/
assert_in.rs

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