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/9.8.3/assertables/macro.assert_in.html\n",
52 " a label: `{}`,\n",
53 " a debug: `{:?}`,\n",
54 " container label: `{}`,\n",
55 " container debug: `{:?}`",
56 ),
57 stringify!($a),
58 a,
59 stringify!($container),
60 container,
61 ))
62 }
63 }
64 }
65 };
66}
67
68#[cfg(test)]
69mod test_assert_in_as_result {
70 use std::sync::Once;
71
72 #[test]
73 fn success() {
74 let a = 1;
75 let b = 0..2;
76 for _ in 0..1 {
77 let actual = assert_in_as_result!(a, b);
78 assert_eq!(actual.unwrap(), ());
79 }
80 }
81
82 #[test]
83 fn success_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_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 failure() {
114 let a = 1;
115 let b = 2..4;
116 let actual = assert_in_as_result!(a, b);
117 let message = concat!(
118 "assertion failed: `assert_in!(a, container)`\n",
119 "https://docs.rs/assertables/9.8.3/assertables/macro.assert_in.html\n",
120 " a label: `a`,\n",
121 " a debug: `1`,\n",
122 " container label: `b`,\n",
123 " container debug: `2..4`"
124 );
125 assert_eq!(actual.unwrap_err(), message);
126 }
127}
128
129/// Assert an item is in a container.
130///
131/// Pseudocode:<br>
132/// a is in container
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!(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!(a, b);
155/// # });
156/// // assertion failed: `assert_in!(a, container)`
157/// // https://docs.rs/assertables/…/assertables/macro.assert_in.html
158/// // a label: `a`,
159/// // a debug: `1`,
160/// // container label: `b`,
161/// // container debug: `2..4`
162/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
163/// # let message = concat!(
164/// # "assertion failed: `assert_in!(a, container)`\n",
165/// # "https://docs.rs/assertables/9.8.3/assertables/macro.assert_in.html\n",
166/// # " a label: `a`,\n",
167/// # " a debug: `1`,\n",
168/// # " container label: `b`,\n",
169/// # " container debug: `2..4`"
170/// # );
171/// # assert_eq!(actual, message);
172/// # }
173/// ```
174///
175/// # Module macros
176///
177/// * [`assert_in`](macro@crate::assert_in)
178/// * [`assert_in_as_result`](macro@crate::assert_in_as_result)
179/// * [`debug_assert_in`](macro@crate::debug_assert_in)
180///
181#[macro_export]
182macro_rules! assert_in {
183 ($a:expr, $container:expr $(,)?) => {
184 match $crate::assert_in_as_result!($a, $container) {
185 Ok(()) => (),
186 Err(err) => panic!("{}", err),
187 }
188 };
189 ($a:expr, $container:expr, $($message:tt)+) => {
190 match $crate::assert_in_as_result!($a, $container) {
191 Ok(()) => (),
192 Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
193 }
194 };
195}
196
197#[cfg(test)]
198mod test_assert_in {
199 use std::panic;
200
201 #[test]
202 fn success() {
203 let a = 1;
204 let b = 0..2;
205 for _ in 0..1 {
206 let actual = assert_in!(a, b);
207 assert_eq!(actual, ());
208 }
209 }
210
211 #[test]
212 fn failure() {
213 let a = 1;
214 let b = 2..4;
215 let result = panic::catch_unwind(|| {
216 let _actual = assert_in!(a, b);
217 });
218 let message = concat!(
219 "assertion failed: `assert_in!(a, container)`\n",
220 "https://docs.rs/assertables/9.8.3/assertables/macro.assert_in.html\n",
221 " a label: `a`,\n",
222 " a debug: `1`,\n",
223 " container label: `b`,\n",
224 " container debug: `2..4`"
225 );
226 assert_eq!(
227 result
228 .unwrap_err()
229 .downcast::<String>()
230 .unwrap()
231 .to_string(),
232 message
233 );
234 }
235}
236
237/// Assert an item is in a container.
238///
239/// Pseudocode:<br>
240/// a is in container
241///
242/// This macro provides the same statements as [`assert_in`](macro.assert_in.html),
243/// except this macro's statements are only enabled in non-optimized
244/// builds by default. An optimized build will not execute this macro's
245/// statements unless `-C debug-assertions` is passed to the compiler.
246///
247/// This macro is useful for checks that are too expensive to be present
248/// in a release build but may be helpful during development.
249///
250/// The result of expanding this macro is always type checked.
251///
252/// An unchecked assertion allows a program in an inconsistent state to
253/// keep running, which might have unexpected consequences but does not
254/// introduce unsafety as long as this only happens in safe code. The
255/// performance cost of assertions, however, is not measurable in general.
256/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
257/// after thorough profiling, and more importantly, only in safe code!
258///
259/// This macro is intended to work in a similar way to
260/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
261///
262/// # Module macros
263///
264/// * [`assert_in`](macro@crate::assert_in)
265/// * [`assert_in`](macro@crate::assert_in)
266/// * [`debug_assert_in`](macro@crate::debug_assert_in)
267///
268#[macro_export]
269macro_rules! debug_assert_in {
270 ($($arg:tt)*) => {
271 if $crate::cfg!(debug_assertions) {
272 $crate::assert_in!($($arg)*);
273 }
274 };
275}