dynamic_matrix/errors/
indexing_error.rs

1//! Error encountered while indexing into a matrix
2
3use std::fmt;
4
5#[derive(Clone, Debug)]
6/// The error type of indexing out of bounds
7pub struct IndexingError {
8    row: usize,
9    col: usize,
10    nrows: usize,
11    ncols: usize,
12}
13
14impl fmt::Display for IndexingError {
15    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
16        let row_error = if self.row >= self.nrows {
17            Some(format!(
18                "Attemped indexing row {}. The row index should be in [0, {})",
19                self.row, self.nrows
20            ))
21        } else {
22            None
23        };
24
25        let col_error = if self.col >= self.ncols {
26            Some(format!(
27                "Attemped indexing column {}. The columns index should be in [0, {})",
28                self.col, self.ncols
29            ))
30        } else {
31            None
32        };
33
34        match (row_error, col_error) {
35            (Some(re), Some(ce)) => writeln!(f, "{}\n{}", re, ce),
36            (Some(e), None) | (None, Some(e)) => writeln!(f, "{}", e),
37            (None, None) => unreachable!(),
38        }
39    }
40}
41
42impl IndexingError {
43    /// Create a new `IndexingError` given the index as a row, column tuple and the shape of the matrix being indexed
44    pub fn new(index: (usize, usize), shape: (usize, usize)) -> IndexingError {
45        IndexingError {
46            row: index.0,
47            col: index.1,
48            nrows: shape.0,
49            ncols: shape.1,
50        }
51    }
52}