core_extensions/macros/
matches_macro.rs

1
2/// Evaluates to true if the expression matches any of the patterns
3/// (this macro can have multiple patterns).
4///
5/// This is equivalent to the [`std::matches`] macro, which requires Rust 1.42.0 .
6///
7/// # Example
8///
9/// ```
10/// use core_extensions::matches;
11///
12/// let some = Some(10);
13/// assert!( matches!(some, Some(10)));
14/// assert!( matches!(some, Some(x) if x == 10));
15/// assert!(!matches!(some, None));
16///
17/// let none = None;
18/// assert!(!matches!(none, Some(10)));
19/// assert!(!matches!(none, Some(x) if x == 10));
20/// assert!( matches!(none, None));
21///
22/// 
23/// for num in &[0, 1, 2, 3][..] {
24///     assert!(matches!(num, 0 | 1 | 2 | 3))
25/// }
26/// 
27/// 
28/// enum Primitive {
29///     Signed(i128),
30///     Unsigned(u128),
31///     Bool(bool),
32///     String(&'static str),
33/// }
34/// 
35/// let prim = Primitive::Bool(false);
36/// assert!(matches!(
37///     prim,
38///     | Primitive::Signed(_)
39///     | Primitive::Unsigned(_)
40///     | Primitive::Bool(_)
41/// ));
42/// 
43/// ```
44/// 
45/// [`std::matches`]: https://doc.rust-lang.org/std/macro.matches.html
46#[macro_export]
47macro_rules! matches {
48    ( $expr:expr, $(|)? $pat:pat $(| $prev_pat:pat)* $(if $cond:expr)?)=>{
49        match $expr {
50            $pat $( | $prev_pat)* =>true,
51            _=>false
52        }
53    };
54}