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
#![allow(trivial_numeric_casts)] use std::fmt; use std::ops::*; use traits::{MatrixRawGet, MatrixGet, MatrixSet, MatrixRawSet, MatrixShape, MatrixSlice, SameShape}; use matrix::write_mat; macro_rules! slice_impl { ($idx_type: ident) => { impl<T: MatrixShape> MatrixSlice<Range<$idx_type>> for T { unsafe fn unsafe_slice(self, range: Range<$idx_type>) -> Slice<T> { Slice::unsafe_new(self, range.start as usize, range.end as usize) } fn slice(self, range: Range<$idx_type>) -> Slice<T> { Slice::new(self, range.start as usize, range.end as usize) } } impl<T: MatrixShape> MatrixSlice<RangeFrom<$idx_type>> for T { unsafe fn unsafe_slice(self, range: RangeFrom<$idx_type>) -> Slice<T> { let l = self.len(); Slice::unsafe_new(self, range.start as usize, l) } fn slice(self, range: RangeFrom<$idx_type>) -> Slice<T> { let l = self.len(); Slice::new(self, range.start as usize, l) } } impl<T: MatrixShape> MatrixSlice<RangeTo<$idx_type>> for T { unsafe fn unsafe_slice(self, range: RangeTo<$idx_type>) -> Slice<T> { Slice::unsafe_new(self, 0, range.end as usize) } fn slice(self, range: RangeTo<$idx_type>) -> Slice<T> { Slice::new(self, 0, range.end as usize) } } } } slice_impl!(usize); slice_impl!(i32); #[derive(Copy)] pub struct Slice<T> { base: T, start: usize, end: usize, } impl<T: MatrixShape> Slice<T> { pub unsafe fn unsafe_new(base: T, start: usize, end: usize) -> Slice<T> { Slice{ base: base, start: start, end: end } } pub fn new(base: T, start: usize, end: usize) -> Slice<T> { assert!(start <= end); assert!(end <= base.len()); Slice{ base: base, start: start, end: end } } } impl<T: MatrixGet<usize>> MatrixRawGet for Slice<T> { unsafe fn raw_get(&self, r: usize, _c: usize) -> f64 { self.base.unsafe_get(r + self.start) } } impl<T: MatrixSet<usize>> MatrixRawSet for Slice<T> { unsafe fn raw_set(&self, r: usize, _c: usize, val: f64) { self.base.unsafe_set(r + self.start, val) } } impl<T> MatrixShape for Slice<T> { fn nrow(&self) -> usize { self.end - self.start } fn ncol(&self) -> usize { 1 } } impl<T: MatrixShape> SameShape for Slice<T> { fn same_shape(&self, nrow: usize, ncol: usize) -> bool { self.nrow() == nrow && self.ncol() == ncol } } impl<T: Clone> Clone for Slice<T> { fn clone(&self) -> Slice<T> { Slice{ base: self.base.clone(), start: self.start, end: self.end } } } impl<T: MatrixRawGet + MatrixShape> fmt::Display for Slice<T> { fn fmt(&self, buf: &mut fmt::Formatter) -> fmt::Result { write_mat(buf, self) } }