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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/// Defines a trait to handle 1D arrays
///
/// # Example
///
/// ```
/// use russell_lab::AsArray1D;
///
/// fn sum<'a, T, U>(array: &'a T) -> f64
/// where
///     T: AsArray1D<'a, U>,
///     U: 'a + Into<f64>,
/// {
///     let mut res = 0.0;
///     let m = array.size();
///     for i in 0..m {
///         res += array.at(i).into();
///     }
///     res
/// }
///
/// // heap-allocated 1D array (vector)
/// let x = vec![1.0, 2.0, 3.0];
/// assert_eq!(sum(&x), 6.0);
///
/// // heap-allocated 1D array (slice)
/// let y: &[f64] = &[10.0, 20.0, 30.0];
/// assert_eq!(sum(&y), 60.0);
///
/// // stack-allocated (fixed-size) 2D array
/// let z = [100.0, 200.0, 300.0];
/// assert_eq!(sum(&z), 600.0);
/// ```
///
/// # Review
///
/// ## Arrays
///
/// Arrays have type `[T; N]` and are a fixed-size list of elements of the same type.
/// Arrays are allocated on the **stack**.
/// Subscripts start at zero.
///
/// ```text
/// let x = [1.0, 2.0, 3.0]; // a: [f64; 3]
/// ```
///
/// Shorthand for initializing each element to 0.0:
///
/// ```text
/// let x = [0.0; 20]; // a: [f64; 20]
/// ```
///
/// ## Vectors
///
/// Vectors are dynamic or "growable" arrays of type `Vec<T>`.
/// Vectors are allocated on the **heap**.
/// We can create vectors with the vec! macro:
///
/// ```text
/// let v = vec![1.0, 2.0, 3.0]; // v: Vec<f64>
/// ```
///
/// ## Slices
///
/// Slices have type `&[T]` and are a reference to (or "view" into) an array.
/// Slices allow efficient access to a portion of an array without copying.
/// A slice is not created directly, but from an existing variable.
/// Slices have a length, can be mutable or not, and in behave like arrays:
///
/// ```text
/// let a = [0.0, 1.0, 2.0, 3.0, 4.0];
/// let middle = &a[1..4]; // A slice of a: just the elements 1.0, 2.0, and 3.0
/// ```
pub trait AsArray1D<'a, U: 'a> {
    /// Returns the size of the array
    fn size(&self) -> usize;

    /// Returns the value at index i
    fn at(&self, i: usize) -> U;
}

/// Defines a heap-allocated 1D array (vector)
impl<'a, U: 'a> AsArray1D<'a, U> for Vec<U>
where
    U: 'a + Copy,
{
    fn size(&self) -> usize {
        self.len()
    }
    fn at(&self, i: usize) -> U {
        self[i]
    }
}

/// Defines a heap-allocated 1D array (slice)
impl<'a, U> AsArray1D<'a, U> for &'a [U]
where
    U: 'a + Copy,
{
    fn size(&self) -> usize {
        self.len()
    }
    fn at(&self, i: usize) -> U {
        self[i]
    }
}

/// Defines a stack-allocated (fixed-size) 1D array
impl<'a, U, const M: usize> AsArray1D<'a, U> for [U; M]
where
    U: 'a + Copy,
{
    fn size(&self) -> usize {
        self.len()
    }
    fn at(&self, i: usize) -> U {
        self[i]
    }
}

/// Defines a trait to handle 2D arrays
///
/// # Example
///
/// ```
/// use russell_lab::AsArray2D;
///
/// fn sum<'a, T, U>(array: &'a T) -> f64
/// where
///     T: AsArray2D<'a, U>,
///     U: 'a + Into<f64>,
/// {
///     let mut res = 0.0;
///     let (m, n) = array.size();
///     for i in 0..m {
///         for j in 0..n {
///             res += array.at(i, j).into();
///         }
///     }
///     res
/// }
///
/// // heap-allocated 2D array (vector of vectors)
/// const IGNORED: f64 = 123.456;
/// let a = vec![
///     vec![1.0, 2.0],
///     vec![3.0, 4.0, IGNORED, IGNORED, IGNORED],
///     vec![5.0, 6.0],
/// ];
/// assert_eq!(sum(&a), 21.0);
///
/// // heap-allocated 2D array (aka slice of slices)
/// let b: &[&[f64]] = &[
///     &[10.0, 20.0],
///     &[30.0, 40.0, IGNORED],
///     &[50.0, 60.0, IGNORED, IGNORED],
/// ];
/// assert_eq!(sum(&b), 210.0);
///
/// // stack-allocated (fixed-size) 2D array
/// let c = [
///     [100.0, 200.0],
///     [300.0, 400.0],
///     [500.0, 600.0],
/// ];
/// assert_eq!(sum(&c), 2100.0);
/// ```
pub trait AsArray2D<'a, U: 'a> {
    /// Returns the (m,n) size of the array
    fn size(&self) -> (usize, usize);

    /// Returns the value at (i,j) indices
    fn at(&self, i: usize, j: usize) -> U;
}

/// Defines a heap-allocated 2D array (vector of vectors)
///
/// # Notes
///
/// * The number of columns is defined by the first row
/// * The next rows must have at least the same number of columns as the first row
impl<'a, U: 'a> AsArray2D<'a, U> for Vec<Vec<U>>
where
    U: 'a + Copy,
{
    fn size(&self) -> (usize, usize) {
        (self.len(), self[0].len())
    }
    fn at(&self, i: usize, j: usize) -> U {
        self[i][j]
    }
}

/// Defines a heap-allocated 2D array (slice of slices)
///
/// # Notes
///
/// * The number of columns is defined by the first row
/// * The next rows must have at least the same number of columns as the first row
impl<'a, U> AsArray2D<'a, U> for &'a [&'a [U]]
where
    U: 'a + Copy,
{
    fn size(&self) -> (usize, usize) {
        (self.len(), self[0].len())
    }
    fn at(&self, i: usize, j: usize) -> U {
        self[i][j]
    }
}

/// Defines a stack-allocated (fixed-size) 2D array
impl<'a, U, const M: usize, const N: usize> AsArray2D<'a, U> for [[U; N]; M]
where
    U: 'a + Copy,
{
    fn size(&self) -> (usize, usize) {
        (self.len(), self[0].len())
    }
    fn at(&self, i: usize, j: usize) -> U {
        self[i][j]
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;
    use std::fmt::Write;

    fn array_1d_str<'a, T, U>(array: &'a T) -> String
    where
        T: AsArray1D<'a, U>,
        U: 'a + std::fmt::Display,
    {
        let mut buf = String::new();
        let m = array.size();
        for i in 0..m {
            write!(&mut buf, "{},", array.at(i)).unwrap();
        }
        write!(&mut buf, "\n").unwrap();
        buf
    }

    fn array_2d_str<'a, T, U>(array: &'a T) -> String
    where
        T: AsArray2D<'a, U>,
        U: 'a + std::fmt::Display,
    {
        let mut buf = String::new();
        let (m, n) = array.size();
        for i in 0..m {
            for j in 0..n {
                write!(&mut buf, "{},", array.at(i, j)).unwrap();
            }
            write!(&mut buf, "\n").unwrap();
        }
        buf
    }

    #[test]
    fn as_array_1d_works() {
        // heap-allocated 1D array (vector)
        let x_data = vec![1.0, 2.0, 3.0];
        assert_eq!(array_1d_str(&x_data), "1,2,3,\n");

        // heap-allocated 1D array (slice)
        let y_data: &[f64] = &[10.0, 20.0, 30.0];
        assert_eq!(array_1d_str(&y_data), "10,20,30,\n");

        // stack-allocated (fixed-size) 2D array
        let z_data = [100.0, 200.0, 300.0];
        assert_eq!(array_1d_str(&z_data), "100,200,300,\n");
    }

    #[test]
    fn as_array_2d_works() {
        // heap-allocated 2D array (vector of vectors)
        const IGNORED: f64 = 123.456;
        let a_data = vec![
            vec![1.0, 2.0],
            vec![3.0, 4.0, IGNORED, IGNORED, IGNORED],
            vec![5.0, 6.0],
        ];
        assert_eq!(
            array_2d_str(&a_data),
            "1,2,\n\
             3,4,\n\
             5,6,\n"
        );

        // heap-allocated 2D array (aka slice of slices)
        let b_data: &[&[f64]] = &[&[10.0, 20.0], &[30.0, 40.0, IGNORED], &[50.0, 60.0, IGNORED, IGNORED]];
        assert_eq!(
            array_2d_str(&b_data),
            "10,20,\n\
             30,40,\n\
             50,60,\n"
        );

        // stack-allocated (fixed-size) 2D array
        let c_data = [[100.0, 200.0], [300.0, 400.0], [500.0, 600.0]];
        assert_eq!(
            array_2d_str(&c_data),
            "100,200,\n\
             300,400,\n\
             500,600,\n"
        );
    }
}