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
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::new(self, nrow, ncol) } } #[derive(Copy)] pub struct Reshape<T> { base: T, nrow: usize, ncol: usize, } impl<T: MatrixShape> Reshape<T> { pub unsafe fn unsafe_new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { Reshape{ base: base, nrow: nrow, ncol: ncol } } pub fn new(base: T, nrow: usize, ncol: usize) -> Reshape<T> { assert!(nrow * ncol == base.len()); Reshape{ base: base, nrow: nrow, ncol: ncol } } } impl<T: MatrixGet<usize>> MatrixRawGet for Reshape<T> { unsafe fn raw_get(&self, r: usize, c: usize) -> f64 { self.base.unsafe_get(r * self.ncol() + c) } } impl<T: MatrixSet<usize>> MatrixRawSet for Reshape<T> { unsafe fn raw_set(&self, r: usize, c: usize, val: f64) { self.base.unsafe_set(r * self.ncol() + c, val) } } impl<T> MatrixShape for Reshape<T> { fn nrow(&self) -> usize { self.nrow } fn ncol(&self) -> usize { self.ncol } } impl<T: MatrixShape> SameShape for Reshape<T> { fn same_shape(&self, nrow: usize, ncol: usize) -> bool { self.nrow() == nrow && self.ncol() == ncol } } impl<T: Clone> Clone for Reshape<T> { fn clone(&self) -> Reshape<T> { Reshape{ base: self.base.clone(), nrow: self.nrow, ncol: self.ncol } } } impl<T: MatrixRawGet + MatrixShape> fmt::Display for Reshape<T> { fn fmt(&self, buf: &mut fmt::Formatter) -> fmt::Result { write_mat(buf, self) } }