md_match/lib.rs
1//! # md-match
2//!
3//! A macro to support md-match.
4//!
5//! ```rust
6//! use md_match::derive::MdMatch;
7//! use md_match::{md_match, MdMatch};
8//!
9//! #[derive(MdMatch)]
10//! enum A {
11//! A1(String),
12//! }
13//!
14//! #[derive(MdMatch)]
15//! enum B {
16//! B1(String),
17//! }
18//!
19//! let (mut a, mut b) = (A::A1(String::from("hello")), B::B1(String::from("world")));
20//!
21//! let (va_ref, vb_ref) = md_match!(&a, &b => |x, y| (x, y));
22//! assert_eq!(va_ref, "hello");
23//! assert_eq!(vb_ref, "world");
24//!
25//! md_match!(&mut a, &mut b => |x, y| {
26//! *x = String::from("world");
27//! *y = String::from("hello");
28//! });
29//!
30//! let (va, vb) = md_match!(a, b => |x, y| (x, y));
31//! assert_eq!(va, "world");
32//! assert_eq!(vb, "hello");
33//! ```
34
35/// derive macro for MdMatch
36pub mod derive {
37 /// derive macro for MdMatch
38 pub use md_match_derive::MdMatch;
39}
40
41/// trait for md-match
42pub trait MdMatch {
43 /// element type
44 type Elem;
45 /// match the element of MdMatch
46 fn md_match<R>(self, f: impl FnOnce(Self::Elem) -> R) -> R;
47}
48
49/// match the element of MdMatch
50#[macro_export]
51macro_rules! md_match {
52 ($e: expr => |$var: pat_param| $body: expr) => {
53 ($e).md_match(|$var| $body)
54 };
55 ($e: expr, $($es: expr),+ => |$var: pat_param, $($vars: pat_param),+| $body: expr) => {
56 ($e).md_match(|$var| md_match!($($es),* => |$($vars),*| $body))
57 };
58}