1use xingo_sparse::{DenseBlock, Real};
34
35use crate::StatlaError;
36
37#[derive(Clone, Copy, Debug)]
42pub struct MatRef<'a, T: Real = f64> {
43 rows: usize,
44 cols: usize,
45 ld: usize,
46 data: &'a [T],
47}
48
49#[derive(Debug)]
51pub struct MatMut<'a, T: Real = f64> {
52 rows: usize,
53 cols: usize,
54 ld: usize,
55 data: &'a mut [T],
56}
57
58fn extent(rows: usize, cols: usize, ld: usize, len: usize) -> Result<usize, StatlaError> {
60 if ld < rows {
62 return Err(StatlaError::InvalidArgument { what: "ld < rows" });
63 }
64 let need = if cols == 0 {
66 0
67 } else {
68 ld.checked_mul(cols - 1)
69 .and_then(|v| v.checked_add(rows))
70 .ok_or(StatlaError::InvalidArgument {
71 what: "view extent overflows usize",
72 })?
73 };
74 if len < need {
76 return Err(StatlaError::Dimension {
77 what: "data",
78 expected: need,
79 found: len,
80 });
81 }
82 Ok(need)
83}
84
85impl<'a, T: Real> MatRef<'a, T> {
86 pub fn new(rows: usize, cols: usize, ld: usize, data: &'a [T]) -> Result<Self, StatlaError> {
92 extent(rows, cols, ld, data.len())?;
93 Ok(Self {
94 rows,
95 cols,
96 ld,
97 data,
98 })
99 }
100 #[must_use]
106 pub fn from_block(b: &'a DenseBlock<T>) -> Self {
107 let cols = if b.data.len() >= b.rows.saturating_mul(b.cols) {
108 b.cols
109 } else {
110 0
111 };
112 Self {
113 rows: b.rows,
114 cols,
115 ld: b.rows,
116 data: &b.data,
117 }
118 }
119 #[must_use]
121 pub fn rows(&self) -> usize {
122 self.rows
123 }
124 #[must_use]
126 pub fn cols(&self) -> usize {
127 self.cols
128 }
129 #[must_use]
131 pub fn ld(&self) -> usize {
132 self.ld
133 }
134 #[must_use]
136 pub fn get(&self, i: usize, j: usize) -> Option<T> {
137 if i < self.rows && j < self.cols {
138 Some(self.data[i + j * self.ld])
139 } else {
140 None
141 }
142 }
143 #[must_use]
145 pub fn col(&self, j: usize) -> Option<&'a [T]> {
146 if j < self.cols {
147 let s = j * self.ld;
148 Some(&self.data[s..s + self.rows])
149 } else {
150 None
151 }
152 }
153 pub fn cols_range(&self, j0: usize, j1: usize) -> Result<Self, StatlaError> {
158 if j0 > j1 || j1 > self.cols {
159 return Err(StatlaError::InvalidArgument {
160 what: "column range outside the view",
161 });
162 }
163 let start = (j0 * self.ld).min(self.data.len());
164 Ok(Self {
165 rows: self.rows,
166 cols: j1 - j0,
167 ld: self.ld,
168 data: &self.data[start..],
169 })
170 }
171 pub(crate) fn raw(&self) -> &'a [T] {
174 self.data
175 }
176 #[must_use]
178 pub fn to_block(&self) -> DenseBlock<T> {
179 let mut b = DenseBlock::zeros(self.rows, self.cols);
180 for j in 0..self.cols {
181 let s = j * self.ld;
182 b.data[j * self.rows..(j + 1) * self.rows]
183 .copy_from_slice(&self.data[s..s + self.rows]);
184 }
185 b
186 }
187}
188
189impl<'a, T: Real> MatMut<'a, T> {
190 pub fn new(
195 rows: usize,
196 cols: usize,
197 ld: usize,
198 data: &'a mut [T],
199 ) -> Result<Self, StatlaError> {
200 extent(rows, cols, ld, data.len())?;
201 Ok(Self {
202 rows,
203 cols,
204 ld,
205 data,
206 })
207 }
208 pub fn from_block(b: &'a mut DenseBlock<T>) -> Self {
211 let cols = if b.data.len() >= b.rows.saturating_mul(b.cols) {
212 b.cols
213 } else {
214 0
215 };
216 Self {
217 rows: b.rows,
218 cols,
219 ld: b.rows,
220 data: &mut b.data,
221 }
222 }
223 #[must_use]
225 pub fn as_ref(&self) -> MatRef<'_, T> {
226 MatRef {
227 rows: self.rows,
228 cols: self.cols,
229 ld: self.ld,
230 data: self.data,
231 }
232 }
233 #[must_use]
235 pub(crate) fn rows(&self) -> usize {
236 self.rows
237 }
238 #[must_use]
240 pub(crate) fn cols(&self) -> usize {
241 self.cols
242 }
243 pub fn col_mut(&mut self, j: usize) -> Option<&mut [T]> {
245 if j < self.cols {
246 let s = j * self.ld;
247 Some(&mut self.data[s..s + self.rows])
248 } else {
249 None
250 }
251 }
252}
253
254#[cfg(test)]
255#[allow(clippy::float_cmp)] mod tests {
257 use super::*;
258
259 #[test]
260 fn views_index_with_the_leading_dimension() {
261 let data = [1.0, 2.0, 99.0, 3.0, 4.0, 99.0, 5.0, 6.0];
263 let a = MatRef::new(2, 3, 3, &data).unwrap();
264 assert_eq!((a.rows(), a.cols(), a.ld()), (2, 3, 3));
265 assert_eq!(a.get(1, 2), Some(6.0));
266 assert_eq!(a.get(2, 0), None);
267 assert_eq!(a.get(0, 3), None);
268 assert_eq!(a.col(1), Some(&[3.0, 4.0][..]));
269 assert_eq!(a.col(3), None);
270 let b = a.to_block();
271 assert_eq!(b.data, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
272 let c = a.cols_range(1, 3).unwrap();
273 assert_eq!(
274 (c.cols(), c.get(0, 0), c.get(1, 1)),
275 (2, Some(3.0), Some(6.0))
276 );
277 let e = a.cols_range(3, 3).unwrap();
278 assert_eq!((e.cols(), e.col(0)), (0, None));
279 assert!(a.cols_range(2, 1).is_err() && a.cols_range(0, 4).is_err());
280 assert_eq!(MatRef::from_block(&b).get(1, 2), Some(6.0));
281 }
282
283 #[test]
284 fn construction_is_checked() {
285 let data = [0.0; 5];
286 assert_eq!(
287 MatRef::new(3, 2, 2, &data).unwrap_err(),
288 StatlaError::InvalidArgument { what: "ld < rows" }
289 );
290 assert_eq!(
291 MatRef::new(3, 2, 3, &data).unwrap_err(),
292 StatlaError::Dimension {
293 what: "data",
294 expected: 6,
295 found: 5
296 }
297 );
298 assert!(MatRef::new(usize::MAX, 3, usize::MAX, &data).is_err());
299 assert!(MatRef::<f64>::new(0, 0, 0, &[]).is_ok());
300 assert!(MatRef::<f64>::new(4, 0, 4, &[]).is_ok());
301 let inconsistent = DenseBlock {
302 rows: 2,
303 cols: 2,
304 data: vec![1.0],
305 };
306 assert_eq!(MatRef::from_block(&inconsistent).cols(), 0);
307 }
308
309 #[test]
310 fn mutable_views_write_through() {
311 let mut data = vec![0.0; 8];
312 {
313 let mut m = MatMut::new(2, 3, 3, &mut data).unwrap();
314 m.col_mut(2).unwrap()[1] = 8.0;
315 assert!(m.col_mut(3).is_none());
316 assert_eq!(m.as_ref().get(1, 2), Some(8.0));
317 }
318 assert_eq!(data[7], 8.0);
319 let mut b = DenseBlock::<f64>::zeros(2, 2);
320 MatMut::from_block(&mut b).col_mut(1).unwrap()[0] = 3.0;
321 assert_eq!(b.get(0, 1), 3.0);
322 assert!(MatMut::new(3, 1, 2, &mut data).is_err());
323 }
324}