nsys-mat 0.5.4

Dynamically sized 2d storage with rectangular iterators and in-place resizing
Documentation
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Dynamically sized 2d storage with rectangular iterators and in-place
//! resizing

#[cfg(feature="serde")]
use serde::{Deserialize, Serialize};

pub mod coordinate;
pub mod dimensions;
pub mod rectangle;
pub use self::coordinate::Coordinate;
pub use self::dimensions::Dimensions;
pub use self::rectangle::Rectangle;

/// Container for 2D data
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Mat <T> {
  elements   : Vec <T>,
  dimensions : Dimensions
}

/// Iterator over a sub-rectangle within a `Mat`.
///
/// &#9888; Note this iterator proceeds *by row*, so the sequence for a
/// an Nx3 rectangle would proceed as: `(0,0)`, `(0,1)`, `(0,2)`,
/// `(1,0)`, `(1,1)`, ...
pub struct RectIter <'a, T : 'a> {
  mat       : &'a Mat <T>,
  rectangle : Rectangle,
  current   : Coordinate
}

/// Mutable iterator over a sub-rectangle within a `Mat`.
///
/// Note this iterator proceeds *by row*, so the sequence for a an Nx3 rectangle
/// would proceed as: `(0,0)`, `(0,1)`, `(0,2)`, `(1,0)`, `(1,1)`, ...
pub struct RectIterMut <'a, T : 'a> {
  mat       : &'a mut Mat <T>,
  rectangle : Rectangle,
  current   : Coordinate
}

impl <T> Mat <T> {
  /// Create a Mat with the given `dimensions`. All elements are initialized as
  /// copies of the given element
  #[inline]
  pub fn fill_with (dimensions : Dimensions, element : &T) -> Self where
    T : Clone
  {
    Mat {
      elements: vec![element.clone(); dimensions.area()],
      dimensions
    }
  }
  /// Create a Mat with the given dimensions filled with default elements
  #[inline]
  pub fn with_dimensions (dimensions : Dimensions) -> Self where
    T : Clone + Default
  {
    Self::fill_with (dimensions, &T::default())
  }
  /// Create a Mat with the given `dimensions` and elements.
  ///
  /// None is returned if the `dimensions` does not match the length of
  /// elements.
  #[inline]
  pub fn from_vec (dimensions : Dimensions, elements : Vec <T>)
    -> Option <Self>
  {
    if dimensions.area() == elements.len() {
      Some (Mat { elements, dimensions })
    } else {
      None
    }
  }
  #[inline]
  pub fn dimensions (&self) -> Dimensions {
    self.dimensions
  }
  /// Returns element at the given coord or `None` if the coord is outside the
  /// Mat.
  ///
  /// # Example
  ///
  /// ```
  /// # use mat::Mat;
  /// let m = Mat::from_vec (
  ///   (3, 3).into(), vec!['a','b','c','d','e','f','g','h','i']
  /// ).unwrap();
  /// assert_eq!(m.get_rc (0, 1), Some(&'b'));
  /// assert_eq!(m.get_rc (2, 1), Some(&'h'));
  /// assert_eq!(m.get_rc (0, 3), None);
  /// ```
  #[inline]
  pub fn get (&self, Coordinate { row, column } : Coordinate) -> Option <&T> {
    self.get_rc (row, column)
  }
  #[inline]
  pub fn get_rc (&self, row : usize, column : usize) -> Option <&T> {
    if self.dimensions.contains_rc (row, column) {
      let i = row * self.width() + column;
      Some (&self.elements[i])
    } else {
      None
    }
  }
  #[inline]
  pub fn get_mut (&mut self, Coordinate { row, column } : Coordinate)
    -> Option <&mut T>
  {
    self.get_mut_rc (row, column)
  }
  /// Returns a mutable reference to the element at the given coord or
  /// `None` if the coord is outside the Mat.
  ///
  /// # Example
  ///
  /// ```
  /// # extern crate mat; use mat::*;
  /// # fn main () {
  /// let mut m = Mat::from_vec (
  ///   (3, 3).into(),
  ///   vec!['a','b','c','d','e','f','g','h','i']
  /// ).unwrap();
  /// assert_eq!(m.get_mut ((0, 1).into()), Some(&mut 'b'));
  /// assert_eq!(m.get_mut ((2, 1).into()), Some(&mut 'h'));
  /// assert_eq!(m.get_mut ((0, 3).into()), None);
  /// # }
  /// ```
  #[inline]
  pub fn get_mut_rc (&mut self, row : usize, column : usize)
    -> Option <&mut T>
  {
    if self.dimensions.contains_rc (row, column) {
      let i = row * self.dimensions.columns + column;
      Some (&mut self.elements[i])
    } else {
      None
    }
  }
  #[inline]
  pub const fn width (&self) -> usize {
    self.dimensions.columns
  }
  #[inline]
  pub const fn height (&self) -> usize {
    self.dimensions.rows
  }
  #[inline]
  pub fn rectangle (&self) -> Rectangle {
    self.dimensions.into()
  }
  #[inline]
  pub fn row (&self, row : usize) -> Option <Rectangle> {
    self.dimensions.row (row)
  }
  #[inline]
  pub fn column (&self, column : usize) -> Option <Rectangle> {
    self.dimensions.column (column)
  }
  #[inline]
  pub fn top (&self) -> Option <Rectangle> {
    self.dimensions.top()
  }
  #[inline]
  pub fn bottom (&self) -> Option <Rectangle> {
    self.dimensions.bottom()
  }
  #[inline]
  pub fn left (&self) -> Option <Rectangle> {
    self.dimensions.left()
  }
  #[inline]
  pub fn right (&self) -> Option <Rectangle> {
    self.dimensions.right()
  }
  /// Resize *in-place* so that `dimensions()` is equal to `new_dimensions`.
  ///
  /// Note that this does not reflow the contents, the new contents will just be
  /// the first elements up to the new total length.
  #[inline]
  pub fn resize (&mut self, dimensions : Dimensions, element : T) where
    T : Clone
  {
    self.elements.resize (dimensions.area(), element);
    self.dimensions = dimensions;
  }
  pub fn flip_horizontal (&mut self) -> &mut Self {
    let cols = self.dimensions.columns;
    let rows = self.dimensions.rows;
    for row in 0..rows {
      let min = row * cols;
      let max = row * cols + cols;
      self.elements[min..max].reverse();
    }
    self
  }
  pub fn flip_vertical (&mut self) -> &mut Self {
    self.elements.reverse();
    self.flip_horizontal()
  }
  #[inline]
  pub fn to_vec (self) -> Vec <T> {
    self.elements
  }
  /// Iterate over the entire Mat
  #[inline]
  #[allow(mismatched_lifetime_syntaxes)]
  pub fn elements (&self) -> std::slice::Iter <T> {
    self.elements.iter()
  }
  /// Mutable iterater over the entire Mat
  #[inline]
  #[allow(mismatched_lifetime_syntaxes)]
  pub fn elements_mut (&mut self) -> std::slice::IterMut <T> {
    self.elements.iter_mut()
  }
  #[inline]
  #[allow(mismatched_lifetime_syntaxes)]
  pub fn rows (&self) -> std::slice::Chunks <T> {
    self.elements.chunks (self.width())
  }
  #[inline]
  #[allow(mismatched_lifetime_syntaxes)]
  pub fn rows_mut (&mut self) -> std::slice::ChunksMut <T> {
    let width = self.width();
    self.elements.chunks_mut (width)
  }
  /// Create an iterator over a rectangular region of the Mat.
  ///
  /// None is returned if the given `rectangle` does not fit entirely within the
  /// Mat.
  pub fn rect_iter <'a> (&'a self, rectangle : Rectangle)
    -> Option <RectIter <'a, T>>
  {
    if self.dimensions.contains (rectangle.min()) &&
      self.dimensions.contains (rectangle.max())
    {
      let current = rectangle.min();
      Some (RectIter { mat: self, rectangle, current })
    } else {
      None
    }
  }
  /// Create a mutable iterator over a rectangular region of the Mat.
  ///
  /// None is returned if the given `rectangle` does not fit entirely within the
  /// Mat.
  pub fn rect_iter_mut <'a> (&'a mut self, rectangle : Rectangle)
    -> Option <RectIterMut <'a, T>>
  {
    /*FIXME:debug*/ println!("DIMENSIONS: {:?}", self.dimensions);
    /*FIXME:debug*/ println!("RECT: {:?}", rectangle);
    if self.dimensions.contains (rectangle.max()) &&
      self.dimensions.contains (rectangle.min())
    {
      let current = rectangle.min();
      Some (RectIterMut { mat: self, rectangle, current })
    } else {
      None
    }
  }
}
impl <T : Clone> Mat <T> {
  pub fn rotate_cw (&mut self) -> &mut Self {
    let len = self.elements.len();
    let mut v = Vec::with_capacity (len);
    for col in 0..self.dimensions.columns {
      for row in 0..self.dimensions.rows {
        let row = self.dimensions.rows - row - 1;
        v.push (self.get_rc (row, col).unwrap().clone());
      }
    }
    debug_assert_eq!(v.len(), len);
    self.elements = v;
    self
  }
  pub fn rotate_ccw (&mut self) -> &mut Self {
    let len = self.elements.len();
    let mut v = Vec::with_capacity (len);
    for col in 0..self.dimensions.columns {
      let col = self.dimensions.columns - col - 1;
      for row in 0..self.dimensions.rows {
        v.push (self.get_rc (row, col).unwrap().clone());
      }
    }
    debug_assert_eq!(v.len(), len);
    self.elements = v;
    self
  }
  #[inline]
  pub fn tranpose (&mut self) -> &mut Self {
    self.rotate_cw().flip_horizontal()
  }
}
impl <T> std::ops::Deref for Mat <T> {
  type Target = Vec <T>;
  fn deref (&self) -> &Vec <T> {
    &self.elements
  }
}
impl <T : std::fmt::Debug> Mat <T> {
  pub fn write_formatted <W : std::io::Write>
    (&self, w : &mut W) -> std::io::Result <()>
  {
    let mut columns = Vec::new();
    for column in 0..self.width() {
      let v = self.rect_iter (self.column (column).unwrap()).unwrap()
        .map (|(_, element)| format!("{:?}", element))
        .collect::<Vec <String>>();
      let longest = v.iter().map (String::len).max().unwrap();
      columns.push ((longest, v));
    }
    for row in 0..self.height() {
      for column in 0..self.width() {
        use std::iter::FromIterator;
        let (longest, col) = &columns[column];
        let s     = &col[row];
        let space = longest - s.len() + 1;
        write!(w, "{}{}", s,
          String::from_iter (std::iter::repeat (' ').take (space)))?;
      }
      writeln!(w)?;
    }
    Ok (())
  }
}
impl <T : std::fmt::Display> std::fmt::Display for Mat <T> {
  fn fmt (&self, f : &mut std::fmt::Formatter <'_>) -> std::fmt::Result {
    let mut columns = Vec::new();
    for column in 0..self.width() {
      let v = self.rect_iter (self.column (column).unwrap()).unwrap()
        .map (|(_, element)| format!("{}", element))
        .collect::<Vec <String>>();
      let longest = v.iter().map (String::len).max().unwrap();
      columns.push ((longest, v));
    }
    for row in 0..self.height() {
      for column in 0..self.width() {
        use std::iter::FromIterator;
        let (longest, col) = &columns[column];
        let s     = &col[row];
        let space = longest - s.len() + 1;
        write!(f, "{}{}", s,
          String::from_iter (std::iter::repeat (' ').take (space)))?;
      }
      writeln!(f)?;
    }
    Ok (())
  }
}

impl <'a, T> Iterator for RectIter <'a, T> {
  type Item = (Coordinate, &'a T);
  fn next (&mut self) -> Option <Self::Item> {
    if self.current.row <= self.rectangle.max().row {
      let next = (self.current, self.mat.get (self.current).unwrap());
      self.current.column += 1;
      if self.current.column > self.rectangle.max().column {
        self.current.column = self.rectangle.min().column;
        self.current.row += 1;
      }
      Some (next)
    } else {
      None
    }
  }
}

impl <'a, T> Iterator for RectIterMut <'a, T> {
  type Item = (Coordinate, &'a mut T);
  fn next (&mut self) -> Option <Self::Item> {
    if self.current.row <= self.rectangle.max().row {
      let coordinate = self.current;
      let element    = unsafe {
        &mut *(self.mat.get_mut (coordinate).unwrap() as *mut T)
      };
      self.current.column += 1;
      if self.current.column > self.rectangle.max().column {
        self.current.column = self.rectangle.min().column;
        self.current.row += 1;
      }
      Some ((coordinate, element))
    } else {
      None
    }
  }
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  fn test_rect_iter_mut() {
    let elements  = vec![1, 2, 3, 4];
    let mut mat   = Mat::from_vec ((2, 2).into(), elements).unwrap();
    let rectangle = Rectangle::from (((0, 0).into(), (2, 2).into()));
    let mut actual_coords = Vec::new();
    for (coord, elem) in mat.rect_iter_mut (rectangle).unwrap() {
      *elem = -(*elem);
      actual_coords.push ((coord.row, coord.column));
    }
    assert_eq!(actual_coords, [(0, 0), (0, 1), (1, 0), (1, 1)]);
    assert_eq!(mat.elements, [-1, -2, -3, -4]);
  }

  #[test]
  fn test_two_iterators() {
    let dimensions = (2, 3).into();
    let m = Mat::from_vec (dimensions, vec![0, 1, 2, 3, 4, 5]).unwrap();
    let iter1 = m.rect_iter (dimensions.into()).unwrap();
    let iter2 = m.rect_iter (dimensions.into()).unwrap();
    for ((coord1, elem1), (coord2, elem2)) in iter1.zip (iter2) {
      assert_eq!(coord1, coord2);
      assert_eq!(elem1, elem2);
    }
  }

  #[test]
  fn test_rect_iter() {
    let dimensions = (3, 3).into();
    let m = Mat::from_vec (dimensions, vec![0, 1, 2, 3, 4, 5, 6, 7, 8])
      .unwrap();
    let dimensions = Dimensions::from ((2, 2));
    let mut iter = m.rect_iter (dimensions.into()).unwrap();
    let (coord, elem) = iter.next().unwrap();
    assert_eq!((coord, *elem), (Coordinate {row: 0, column: 0}, 0));
    let (coord, elem) = iter.next().unwrap();
    assert_eq!((coord, *elem), (Coordinate {row: 0, column: 1}, 1));
    let (coord, elem) = iter.next().unwrap();
    assert_eq!((coord, *elem), (Coordinate {row: 1, column: 0}, 3));
    let (coord, elem) = iter.next().unwrap();
    assert_eq!((coord, *elem), (Coordinate {row: 1, column: 1}, 4));
    assert!(iter.next().is_none());
  }
}