dynamic_matrix/errors/
shape_error.rs

1//! Error encountered due to incompatible shapes
2
3use std::fmt;
4
5#[derive(Clone, Debug)]
6/// The error type for any shape errors
7pub struct ShapeError {
8    rows: usize,
9    cols: usize,
10    expected_rows: usize,
11    expected_cols: usize,
12}
13
14impl fmt::Display for ShapeError {
15    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
16        if self.rows != self.expected_rows {
17            writeln!(
18                f,
19                "The operation performed expected {} rows but the matrix has {}.",
20                self.expected_rows, self.rows
21            )
22        } else {
23            writeln!(
24                f,
25                "The operation performed expected {} cols but the matrix has {}.",
26                self.expected_cols, self.cols
27            )
28        }
29    }
30}
31
32impl ShapeError {
33    /// Create a new `ShapeError` given the shape of the matrix and the expected shape
34    pub fn new(shape: (usize, usize), expected_shape: (usize, usize)) -> ShapeError {
35        ShapeError {
36            rows: shape.0,
37            cols: shape.1,
38            expected_rows: expected_shape.0,
39            expected_cols: expected_shape.1,
40        }
41    }
42
43    /// Create a new `ShapeError` given the rows of the matrix and the expected rows
44    pub fn new_rows_error(rows: usize, expected_rows: usize) -> ShapeError {
45        ShapeError {
46            rows,
47            cols: 0,
48            expected_rows,
49            expected_cols: 0,
50        }
51    }
52
53    /// Create a new `ShapeError` given the columns of the matrix and the expected columns
54    pub fn new_cols_error(cols: usize, expected_cols: usize) -> ShapeError {
55        ShapeError {
56            rows: 0,
57            cols,
58            expected_rows: 0,
59            expected_cols,
60        }
61    }
62}