1use std::fmt;
4
5#[derive(Clone, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Error {
12 InvalidInput(String),
15 Evaluation(String),
18 Unsupported(String),
20 Backend(String),
22}
23
24impl fmt::Display for Error {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 match self {
27 Error::InvalidInput(m) => write!(f, "invalid input: {m}"),
28 Error::Evaluation(m) => write!(f, "evaluation failed: {m}"),
29 Error::Unsupported(m) => write!(f, "unsupported: {m}"),
30 Error::Backend(m) => write!(f, "backend failed: {m}"),
31 }
32 }
33}
34
35impl std::error::Error for Error {}
36
37impl Error {
38 pub fn message(&self) -> &str {
40 match self {
41 Error::InvalidInput(m)
42 | Error::Evaluation(m)
43 | Error::Unsupported(m)
44 | Error::Backend(m) => m,
45 }
46 }
47}
48
49pub type Result<T> = std::result::Result<T, Error>;
51
52pub(crate) fn ensure(ok: bool, message: impl FnOnce() -> String) -> Result<()> {
54 if ok {
55 Ok(())
56 } else {
57 Err(Error::InvalidInput(message()))
58 }
59}
60
61pub(crate) fn first_non_finite(values: &[f64]) -> Option<(usize, f64)> {
63 values
64 .iter()
65 .copied()
66 .enumerate()
67 .find(|(_, v)| !v.is_finite())
68}
69
70pub(crate) fn ensure_finite(values: &[f64], what: &str) -> Result<()> {
72 match first_non_finite(values) {
73 Some((i, v)) => Err(Error::InvalidInput(format!("{what}: entry {i} is {v}"))),
74 None => Ok(()),
75 }
76}
77
78pub(crate) fn finite(value: f64, what: &str) -> Result<f64> {
80 if value.is_finite() {
81 Ok(value)
82 } else {
83 Err(Error::Evaluation(format!(
84 "{what} overflowed or became nonfinite"
85 )))
86 }
87}