const generic expr based fixed length array manipulation crate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/// Turn a tuple into a array. Implemented for N≤32
pub trait Array<const N: usize, T> {
    /// Turn a tuple into a array
    fn array(self) -> [T; N];
}

/// Turn a array into a tuple. Implemented for N≤32
pub trait Tuple<O> {
    /// Turn a array into a tuple.
    fn tuple(self) -> O;
}

// thanks yandros
macro_rules! with_vars {
    (
        [acc: $($acc:tt)*]
        [to_munch: T $($rest:tt)*]
        $($cb:tt)*
    ) => (with_vars! {
        [acc: $($acc)* x]
        [to_munch: $($rest)*]
        $($cb)*
    });

    (
        [acc: $($var:ident)*]
        [to_munch: /* nothing */]
        |$_:tt $metavar:ident| $body:tt
    ) => ({
        macro_rules! __emit__ {(
            $_( $_ $metavar:ident)*
        ) =>
            $body
        }
        __emit__! { $($var)* }
    });
}

macro_rules! generate {(
    $($Hd:tt $($T:tt)*)?
) => (
    $(generate! { $($T)* })?
    do_impl! { [$] $($Hd $($T)*)? }
)}
macro_rules! do_impl {(
    [$_:tt] // `$` sigil
    $($i:tt)*
) => (
    impl<T> Tuple<($($i, )*)> for [T; 0 $(+ { stringify!($i); 1 } )*] {
        fn tuple(self) -> ($($i, )*) {
            with_vars! {
                [acc: ]
                [to_munch: $($i)*]
                |$_ x| {
                    let [$_($x, )*] = self;
                    ($_($x, )*)
                }
            }
        }
    }

    impl<T> Array<{ 0 $(+ { stringify!($i); 1 } )* }, T> for ($($i, )*) {
        fn array(self) -> [T; 0 $(+ { stringify!($i); 1 } )*] {
            with_vars! {
                [acc: ]
                [to_munch: $($i)*]
                |$_ x| {
                    let ($_($_ x, )*) = self;
                    [$_($_ x, )*]
                }
            }
        }
    }
)}

generate! {
    T T T T  T T T T
    T T T T  T T T T
    T T T T  T T T T
    T T T T  T T T T
    T T T T  T T T T
}