pub trait AsMatrix<'a, U: 'a> {
fn size(&self) -> (usize, usize);
fn at(&self, i: usize, j: usize) -> U;
}
impl<'a, U: 'a> AsMatrix<'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]
}
}
impl<'a, U> AsMatrix<'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]
}
}
impl<'a, U, const M: usize, const N: usize> AsMatrix<'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::AsMatrix;
use std::fmt::Write;
fn matrix_str<'a, T, U>(array: &'a T) -> String
where
T: AsMatrix<'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_matrix_works() {
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!(
matrix_str(&a),
"1,2,\n\
3,4,\n\
5,6,\n"
);
let b: &[&[f64]] = &[&[10.0, 20.0], &[30.0, 40.0, IGNORED], &[50.0, 60.0, IGNORED, IGNORED]];
assert_eq!(
matrix_str(&b),
"10,20,\n\
30,40,\n\
50,60,\n"
);
let c = [[100.0, 200.0], [300.0, 400.0], [500.0, 600.0]];
assert_eq!(
matrix_str(&c),
"100,200,\n\
300,400,\n\
500,600,\n"
);
}
}