Skip to main content

sundials_rs/
error.rs

1use thiserror::Error;
2
3#[derive(Debug, Error)]
4pub enum SundialsError {
5    #[error("memory allocation failed in {0}")]
6    Memory(&'static str),
7
8    #[error("{solver} returned error code {code} in {function}")]
9    ReturnCode {
10        solver: &'static str,
11        function: &'static str,
12        code: i32,
13    },
14
15    #[error("right-hand side function returned non-zero flag {0}")]
16    RhsError(i32),
17
18    #[error("N_Vector creation failed")]
19    NVectorCreate,
20
21    #[error("SUNMatrix creation failed")]
22    MatrixCreate,
23
24    #[error("SUNLinearSolver creation failed")]
25    LinearSolverCreate,
26
27    #[error("step size became too small")]
28    TooMuchWork,
29
30    #[error("solution appears to diverge")]
31    Diverge,
32}
33
34/// Map a SUNDIALS integer flag to `Ok(())` or an appropriate `Err`.
35pub(crate) fn check_flag(
36    flag: std::os::raw::c_int,
37    solver: &'static str,
38    function: &'static str,
39) -> Result<(), SundialsError> {
40    // Flag values are defined per-solver in their respective headers.
41    // 0 is CV_SUCCESS / IDA_SUCCESS for all solvers.
42    if flag >= 0 {
43        Ok(())
44    } else {
45        Err(SundialsError::ReturnCode { solver, function, code: flag })
46    }
47}