use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
InvalidInput(String),
Evaluation(String),
Unsupported(String),
Backend(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidInput(m) => write!(f, "invalid input: {m}"),
Error::Evaluation(m) => write!(f, "evaluation failed: {m}"),
Error::Unsupported(m) => write!(f, "unsupported: {m}"),
Error::Backend(m) => write!(f, "backend failed: {m}"),
}
}
}
impl std::error::Error for Error {}
impl Error {
pub fn message(&self) -> &str {
match self {
Error::InvalidInput(m)
| Error::Evaluation(m)
| Error::Unsupported(m)
| Error::Backend(m) => m,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) fn ensure(ok: bool, message: impl FnOnce() -> String) -> Result<()> {
if ok {
Ok(())
} else {
Err(Error::InvalidInput(message()))
}
}
pub(crate) fn first_non_finite(values: &[f64]) -> Option<(usize, f64)> {
values
.iter()
.copied()
.enumerate()
.find(|(_, v)| !v.is_finite())
}
pub(crate) fn ensure_finite(values: &[f64], what: &str) -> Result<()> {
match first_non_finite(values) {
Some((i, v)) => Err(Error::InvalidInput(format!("{what}: entry {i} is {v}"))),
None => Ok(()),
}
}
pub(crate) fn finite(value: f64, what: &str) -> Result<f64> {
if value.is_finite() {
Ok(value)
} else {
Err(Error::Evaluation(format!(
"{what} overflowed or became nonfinite"
)))
}
}