arr_rs/macros/
create.rs

1/// Create an array
2///
3/// # Examples
4///
5/// ```
6/// use arr_rs::prelude::*;
7///
8/// let arr = array!(i16, 1, 2, 3, 4, 5, 6, 7, 8).unwrap();
9/// let arr = array!(i16, [1, 2, 3, 4, 5, 6, 7, 8]).unwrap();
10/// let arr = array!(i32, [[1, 2], [3, 4], [5, 6], [7, 8]]).unwrap();
11/// let arr = array!(f64, [[1, 2, 3, 4], [5, 6, 7, 8]]).unwrap();
12/// ```
13#[macro_export]
14macro_rules! array {
15    (Tuple2<$t1:ty, $t2:ty>, $($x:expr),* $(,)*) => {{
16        array_tuple!(Tuple2<$t1, $t2>, format!("{:?}", vec![$(vec![$x],)*]))
17    }};
18    (Tuple3<$t1:ty, $t2:ty, $t3:ty>, $($x:expr),* $(,)*) => {{
19        array_tuple!(Tuple3<$t1, $t2, $t3>, format!("{:?}", vec![$($x,)*]))
20    }};
21    (List<$tt:ty>, $x:expr) => {{
22        array_list!(List<$tt>, format!("{:?}", vec![$x]))
23    }};
24    (char, $($x:expr),* $(,)*) => {{
25        array_char!(format!("{:?}", vec![$($x,)*]))
26    }};
27    (String, $($x:expr),* $(,)*) => {{
28        array_string!(format!("{:?}", vec![$($x,)*]))
29    }};
30    ($tt:ty, $($x:expr),* $(,)*) => {{
31        let string = format!("{:?}", vec![$($x,)*])
32            .replace("\", \"", "\",\"")
33            .replace("], [", "],[");
34        let ndim = string.find(|p| p != '[').unwrap_or(1) - 1;
35        let ndim = if ndim == 0 { 1 } else { ndim };
36
37        // get shape
38        let shape = array_parse_shape!(ndim, string.clone());
39
40        // get array elements
41        let elems = string
42            .replace("[", "")
43            .replace("]", "")
44            .replace(", ", ",")
45            .replace("\"", "")
46            .split_terminator(',')
47            .map(|e| e.parse().unwrap())
48            .collect::<Vec<_>>();
49
50        // return array
51        Array::<$tt>::new(elems, shape)
52    }};
53}