Skip to main content

sparse_ir_sve/
error.rs

1//! Error type of the public API
2//!
3//! The public functions of this crate that return a `Result` use [`Error`]
4//! as the error type. Each variant carries the values that caused it, so
5//! that its message locates the problem. The `sparse-ir` crates convert it
6//! into their own error type variant by variant.
7
8/// Error returned by the fallible public functions of this crate
9///
10/// More variants may be added without a major version bump.
11///
12/// Errors compare equal when all their fields do. An error that holds a NaN
13/// value is therefore not equal to itself; match on the variant instead.
14#[derive(Debug, Clone, PartialEq, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17    /// A parameter is outside its valid range.
18    #[error("invalid {name} = {value}: {reason}")]
19    InvalidParameter {
20        /// Name of the parameter, as in the documentation of the function
21        name: &'static str,
22        /// The rejected value, formatted for the message
23        value: String,
24        /// The condition that the value violates, e.g. "must be in (0, 1)"
25        reason: String,
26    },
27    /// A point lies outside the domain of a function, e.g. x outside the
28    /// knots of a polynomial. NaN lies outside every domain.
29    #[error("{name} = {value:?} is outside the domain [{:?}, {:?}]", .domain.0, .domain.1)]
30    OutOfDomain {
31        /// Name of the argument, as in the documentation of the function
32        name: &'static str,
33        /// The rejected point
34        value: f64,
35        /// The closed interval `(lower, upper)` of valid points
36        domain: (f64, f64),
37    },
38    /// An input that must not be empty is empty.
39    #[error("{name} must not be empty")]
40    EmptyInput {
41        /// Name of the input, as in the documentation of the function
42        name: &'static str,
43    },
44    /// An input contains NaN or an infinity.
45    #[error("{name} has the non-finite entry {value} at index {index:?}")]
46    NonFiniteInput {
47        /// Name of the input, as in the documentation of the function
48        name: &'static str,
49        /// Index of the first non-finite entry (`[row, column]` for a matrix)
50        index: Vec<usize>,
51        /// That entry, converted to `f64`
52        value: f64,
53    },
54    /// The operation is not defined for this input, e.g. the even/odd SVE of
55    /// a kernel that is not centrosymmetric.
56    #[error("not supported: {what}")]
57    NotSupported {
58        /// What is not supported, and why
59        what: String,
60    },
61    /// A matrix decomposition failed, e.g. the SVD iteration did not converge.
62    #[error("decomposition failed: {reason}")]
63    DecompositionFailed {
64        /// What failed, with the values involved
65        reason: String,
66    },
67}
68
69/// Category of an [`Error`]: what the caller can do about it
70///
71/// More categories may be added without a major version bump.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73#[non_exhaustive]
74pub enum ErrorKind {
75    /// An argument is invalid: a parameter outside its range, a point
76    /// outside the domain, an empty input or a non-finite entry
77    InvalidArgument,
78    /// The operation is not defined for this input
79    NotSupported,
80    /// A failure that invalid input does not explain, e.g. an SVD iteration
81    /// that did not converge
82    Internal,
83}
84
85impl Error {
86    /// Category of the error
87    pub fn kind(&self) -> ErrorKind {
88        match self {
89            Error::InvalidParameter { .. }
90            | Error::OutOfDomain { .. }
91            | Error::EmptyInput { .. }
92            | Error::NonFiniteInput { .. } => ErrorKind::InvalidArgument,
93            Error::NotSupported { .. } => ErrorKind::NotSupported,
94            Error::DecompositionFailed { .. } => ErrorKind::Internal,
95        }
96    }
97}
98
99/// Result type of the fallible public functions of this crate
100pub type Result<T, E = Error> = std::result::Result<T, E>;
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    /// Every variant has its category
107    #[test]
108    fn test_kind_of_each_variant() {
109        let cases = [
110            (
111                Error::InvalidParameter {
112                    name: "epsilon",
113                    value: "2.0".to_string(),
114                    reason: "must be in (0, 1)".to_string(),
115                },
116                ErrorKind::InvalidArgument,
117            ),
118            (
119                Error::OutOfDomain {
120                    name: "x",
121                    value: 2.0,
122                    domain: (-1.0, 1.0),
123                },
124                ErrorKind::InvalidArgument,
125            ),
126            (Error::EmptyInput { name: "s" }, ErrorKind::InvalidArgument),
127            (
128                Error::NonFiniteInput {
129                    name: "matrix",
130                    index: vec![0, 1],
131                    value: f64::NAN,
132                },
133                ErrorKind::InvalidArgument,
134            ),
135            (
136                Error::NotSupported {
137                    what: "parity".to_string(),
138                },
139                ErrorKind::NotSupported,
140            ),
141            (
142                Error::DecompositionFailed {
143                    reason: "SVD".to_string(),
144                },
145                ErrorKind::Internal,
146            ),
147        ];
148        for (error, kind) in cases {
149            assert_eq!(error.kind(), kind, "{error}");
150        }
151    }
152}