cairo_lang_utils/extract_matches.rs
1/// Macro to try to evaluate an expression as a pattern and extract its fields.
2/// # Examples:
3/// ```
4/// use cairo_lang_utils::try_extract_matches;
5///
6/// #[derive(Debug, Clone, Copy)]
7/// struct Point {
8/// x: u32,
9/// y: u32,
10/// }
11/// #[derive(Debug)]
12/// enum MyEnum {
13/// Point(Point),
14/// Value(u32),
15/// }
16/// let p = MyEnum::Point(Point { x: 3, y: 5 });
17/// if let Some(Point { x, y: _ }) = try_extract_matches!(p, MyEnum::Point) {
18/// assert_eq!(x, 3);
19/// }
20/// ```
21#[macro_export]
22macro_rules! try_extract_matches {
23 ($e:expr, $variant:path) => {
24 if let $variant(x) = $e { Some(x) } else { None }
25 };
26}
27
28/// Macro to verify an expression matches a pattern and extract its fields.
29/// # Examples:
30/// ```
31/// use cairo_lang_utils::extract_matches;
32///
33/// #[derive(Debug, Clone, Copy)]
34/// struct Point {
35/// x: u32,
36/// y: u32,
37/// }
38/// #[derive(Debug)]
39/// enum MyEnum {
40/// Point(Point),
41/// Value(u32),
42/// }
43/// let p = MyEnum::Point(Point { x: 3, y: 5 });
44/// let Point { x, y: _ } = extract_matches!(p, MyEnum::Point);
45/// assert_eq!(x, 3);
46///
47/// // Would panic with 'assertion failed: `Point(Point { x: 3, y: 5 })` does not match `MyEnum::Value`:
48/// // Expected a point!'
49/// // let _value = extract_matches!(p, MyEnum::Value, "Expected a point!");
50/// ```
51#[macro_export]
52macro_rules! extract_matches {
53 ($e:expr, $variant:path) => {
54 match $e {
55 $variant(x) => x,
56 ref e => {
57 panic!("Variant extract failed: `{:?}` is not of variant `{}`", e, stringify!($variant))
58 }
59 }
60 };
61 ( $e:expr , $variant:path , $($arg:tt)* ) => {
62 match $e {
63 $variant(x) => x,
64 ref e => panic!("Variant extract failed: `{:?}` is not of variant `{}`: {}",
65 e, stringify!($variant), format_args!($($arg)*))
66 }
67 };
68}