document_tree/
macro_util.rs

1macro_rules! cartesian_impl {
2    ($out:tt [] $b:tt $init_b:tt $submacro:tt) => {
3        $submacro!{$out}
4    };
5    ($out:tt [$a:tt, $($at:tt)*] [] $init_b:tt $submacro:tt) => {
6        cartesian_impl!{$out [$($at)*] $init_b $init_b $submacro}
7    };
8    ([$($out:tt)*] [$a:tt, $($at:tt)*] [$b:tt, $($bt:tt)*] $init_b:tt $submacro:tt) => {
9        cartesian_impl!{[$($out)* ($a, $b),] [$a, $($at)*] [$($bt)*] $init_b $submacro}
10    };
11}
12
13macro_rules! cartesian {
14    ( $submacro:tt, [$($a:tt)*], [$($b:tt)*]) => {
15        cartesian_impl!{[] [$($a)*,] [$($b)*,] [$($b)*,] $submacro}
16    };
17}
18
19#[cfg(test)]
20mod tests {
21    macro_rules! print_cartesian {
22        ( [ $(($a1:tt, $a2:tt)),* , ] ) => {
23            fn test_f(x:i64, y:i64) -> Result<(i64, i64), ()> {
24                match (x, y) {
25                $(
26                    ($a1, $a2) => { Ok(($a1, $a2)) }
27                )*
28                _ => { Err(()) }
29                }
30            }
31        };
32    }
33
34    #[test]
35    fn print_cartesian() {
36        cartesian!(print_cartesian, [1, 2, 3], [4, 5, 6]);
37        assert_eq!(test_f(1, 4), Ok((1, 4)));
38        assert_eq!(test_f(1, 3), Err(()));
39        assert_eq!(test_f(3, 5), Ok((3, 5)));
40    }
41}