counted_array/
lib.rs

1#![cfg_attr(feature = "nightly", feature(allow_internal_unstable, macro_reexport))]
2
3#[cfg(feature = "nightly")]
4#[macro_reexport(lazy_static, __lazy_static_create)]
5#[macro_use]
6extern crate lazy_static;
7
8#[cfg(feature = "nightly")]
9pub use lazy_static::lazy;
10
11/// Declare a fixed-size array with an autogenerated length.
12///
13/// ```
14/// # #[macro_use] extern crate counted_array;
15/// # fn main() {
16/// counted_array!(let arr: [i32; _] = [1, 2, 3]);
17/// assert_eq!(arr.len(), 3);
18/// # }
19/// ```
20#[macro_export]
21macro_rules! counted_array {
22    // INTERNAL
23
24    // last element (proceed to output)
25    (@parse $size:expr, ($val:expr) -> [$($accs:expr),*] $thru:tt) => {
26        counted_array!(@output $size + 1usize, [$($accs,)* $val] $thru);
27    };
28    // more elements (keep parsing)
29    (@parse $size:expr, ($val:expr, $($vals:expr),*) -> [$($accs:expr),*] $thru:tt) => {
30        counted_array!(@parse $size + 1usize, ($($vals),*) -> [$($accs,)* $val] $thru);
31    };
32    
33    // output a local variable
34    (@output $size:expr, $acc:tt (() let $n:ident $t:ty)) => {
35        let $n: [$t; $size] = $acc;
36    };
37    // output a lazy static
38    (@output $size:expr, $acc:tt (($($p:tt)*) lazy_static $n:ident $t:ty)) => {
39        lazy_static!{ $($p)* static ref $n: [$t; $size] = $acc; }
40    };
41    // output a static or const item
42    (@output $size:expr, $acc:tt (($($p:tt)*) $s:ident $n:ident $t:ty)) => {
43        $($p)* $s $n: [$t; $size] = $acc;
44    };
45    
46    // EXTERNAL
47    
48    // entry point
49    (pub $storage:ident $n:ident: [$t:ty; _] = [$($vals:expr),* $(,)*]) => {
50        counted_array!(@parse 0usize, ($($vals),*) -> [] ((pub) $storage $n $t));
51    };
52    (pub $restr:tt $storage:ident $n:ident: [$t:ty; _] = [$($vals:expr),* $(,)*]) => {
53        counted_array!(@parse 0usize, ($($vals),*) -> [] ((pub $restr) $storage $n $t));
54    };
55    ($storage:ident $n:ident: [$t:ty; _] = [$($vals:expr),* $(,)*]) => {
56        counted_array!(@parse 0usize, ($($vals),*) -> [] (() $storage $n $t));
57    };
58}
59