assert_matches2/
lib.rs

1#![doc = include_str!("../README.md")]
2#![no_std]
3
4/// Assert that the given expression matches the given pattern, and introduce
5/// any bindings from the pattern into the surrounding scope.
6///
7/// If the assertion fails, the expression before the comma is debug-printed as
8/// part of the panic message.
9#[macro_export]
10macro_rules! assert_matches {
11    ($e:expr, $pat:pat) => {
12        let value = $e;
13        let $pat = value else {
14            ::core::panic!(
15                "match assertion failed\n pattern: `{}`\n   value: `{:?}`",
16                ::core::stringify!($pat), value,
17            );
18        };
19    };
20    ($e:expr, $pat:pat, $($arg:tt)*) => {
21        let value = $e;
22        let $pat = value else {
23            ::core::panic!(
24                "match assertion failed: {}\n pattern: `{}`\n   value: `{:?}`",
25                ::core::format_args!($($arg)*), ::core::stringify!($pat), value,
26            );
27        };
28    };
29}
30
31/// Alternative form of [`assert_matches!`] where the pattern comes first.
32///
33/// If the assertion fails, the expression after the `=` is debug-printed as
34/// part of the panic message.
35///
36/// # Example
37///
38/// ```
39/// use assert_matches2::assert_let;
40/// use serde_json::{json, Value as JsonValue};
41///
42/// let val = json!({ "field": [1, 2, 3] });
43/// assert_let!(JsonValue::Object(obj) = val);
44/// assert_eq!(obj.len(), 1);
45/// assert_let!(Some((field_name, JsonValue::Array(arr))) = obj.into_iter().next());
46/// assert_eq!(field_name, "field");
47/// assert_eq!(arr, [1, 2, 3]);
48/// ```
49#[macro_export]
50macro_rules! assert_let {
51    ($pat:pat = $e:expr) => {
52        $crate::assert_matches!($e, $pat);
53    };
54    ($pat:pat = $e:expr, $($arg:tt)*) => {
55        $crate::assert_matches!($e, $pat, $($arg)*);
56    }
57}