matreex/error.rs
1//! Error handling for the crate.
2
3/// An alias for [`std::result::Result`].
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// An enum for error types.
7#[derive(Copy, Clone, Debug, PartialEq, Eq)]
8pub enum Error {
9 /// Error when matrix size exceeds [`usize::MAX`], which is, in fact
10 /// pointless, since a matrix can only store up to [`isize::MAX`] bytes
11 /// of data.
12 SizeOverflow,
13
14 /// Error when the size of the shape does not match the length of the
15 /// underlying data.
16 ///
17 /// Ensuring this equality is crucial because if the size exceeds the
18 /// length, indexing into the matrix may result in out-of-bounds memory
19 /// access, leading to *[undefined behavior]*.
20 ///
21 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
22 SizeMismatch,
23
24 /// Error when the capacity exceeds [`isize::MAX`].
25 ///
26 /// Refer to [`vec`] and *[The Rustonomicon]* for more information.
27 ///
28 /// [`vec`]: mod@std::vec
29 /// [The Rustonomicon]: https://doc.rust-lang.org/stable/nomicon/vec/vec-alloc.html#allocating-memory
30 CapacityOverflow,
31
32 /// Error when creating a matrix from a sequence of vectors with
33 /// inconsistent lengths.
34 LengthInconsistent,
35
36 /// Error for accessing an index out of bounds.
37 IndexOutOfBounds,
38
39 /// Error when a square matrix is required but the current one does not
40 /// satisfy this requirement.
41 SquareMatrixRequired,
42
43 /// Error when the shapes of two matrices are not conformable for the
44 /// intended operation.
45 ShapeNotConformable,
46}
47
48impl std::fmt::Display for Error {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 let content = match self {
51 Self::SizeOverflow => "size overflow",
52 Self::SizeMismatch => "size mismatch",
53 Self::CapacityOverflow => "capacity overflow",
54 Self::LengthInconsistent => "length inconsistent",
55 Self::IndexOutOfBounds => "index out of bounds",
56 Self::SquareMatrixRequired => "square matrix required",
57 Self::ShapeNotConformable => "shape not conformable",
58 };
59 write!(f, "{content}")
60 }
61}
62
63impl std::error::Error for Error {}