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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use std::slice;
use imp_prelude::*;
pub fn arr0<A>(x: A) -> Array0<A>
{
unsafe { ArrayBase::from_shape_vec_unchecked((), vec![x]) }
}
pub fn arr1<A: Clone>(xs: &[A]) -> Array1<A> {
ArrayBase::from_vec(xs.to_vec())
}
pub fn rcarr1<A: Clone>(xs: &[A]) -> RcArray<A, Ix1> {
arr1(xs).into_shared()
}
pub fn aview0<A>(x: &A) -> ArrayView0<A> {
unsafe { ArrayView::new_(x, (), ()) }
}
pub fn aview1<A>(xs: &[A]) -> ArrayView1<A> {
ArrayView::from(xs)
}
pub fn aview2<A, V: FixedInitializer<Elem=A>>(xs: &[V]) -> ArrayView2<A> {
let cols = V::len();
let rows = xs.len();
let data = unsafe {
slice::from_raw_parts(xs.as_ptr() as *const A, cols * rows)
};
let dim = (rows as Ix, cols as Ix);
unsafe {
let strides = dim.default_strides();
ArrayView::new_(data.as_ptr(), dim, strides)
}
}
pub fn aview_mut1<A>(xs: &mut [A]) -> ArrayViewMut1<A> {
ArrayViewMut::from(xs)
}
pub unsafe trait FixedInitializer {
type Elem;
fn as_init_slice(&self) -> &[Self::Elem];
fn len() -> usize;
}
macro_rules! impl_arr_init {
(__impl $n: expr) => (
unsafe impl<T> FixedInitializer for [T; $n] {
type Elem = T;
fn as_init_slice(&self) -> &[T] { self }
fn len() -> usize { $n }
}
);
() => ();
($n: expr, $($m:expr,)*) => (
impl_arr_init!(__impl $n);
impl_arr_init!($($m,)*);
)
}
impl_arr_init!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,);
pub fn arr2<A: Clone, V: FixedInitializer<Elem = A>>(xs: &[V]) -> Array2<A> {
let (m, n) = (xs.len() as Ix, V::len() as Ix);
let dim = (m, n);
let mut result = Vec::<A>::with_capacity(dim.size());
for snd in xs {
result.extend_from_slice(snd.as_init_slice());
}
unsafe {
ArrayBase::from_shape_vec_unchecked(dim, result)
}
}
pub fn rcarr2<A: Clone, V: FixedInitializer<Elem = A>>(xs: &[V]) -> RcArray<A, Ix2> {
arr2(xs).into_shared()
}
pub fn arr3<A: Clone, V: FixedInitializer<Elem=U>, U: FixedInitializer<Elem=A>>(xs: &[V])
-> Array3<A>
{
let dim = (xs.len() as Ix, V::len() as Ix, U::len() as Ix);
let mut result = Vec::<A>::with_capacity(dim.size());
for snd in xs {
for thr in snd.as_init_slice() {
result.extend_from_slice(thr.as_init_slice());
}
}
unsafe {
ArrayBase::from_shape_vec_unchecked(dim, result)
}
}
pub fn rcarr3<A: Clone, V: FixedInitializer<Elem=U>, U: FixedInitializer<Elem=A>>(xs: &[V])
-> RcArray<A, Ix3>
{
arr3(xs).into_shared()
}