Skip to main content

lp_ip_craft/
error.rs

1//! The error type shared by all components.
2
3use std::fmt;
4
5/// Why a call was aborted.
6///
7/// Errors never carry a partial result: a solve either returns a
8/// [`SolveResult`](crate::SolveResult) or one of these.
9#[derive(Clone, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Error {
12    /// Malformed model data, start point or options. Always detected before
13    /// any work is done.
14    InvalidInput(String),
15    /// Floating-point evaluation failed, for example because a row activity
16    /// overflowed to infinity although every input was finite.
17    Evaluation(String),
18    /// A well-formed request that this component does not implement.
19    Unsupported(String),
20    /// Native backend setup or execution failed.
21    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    /// The message without the category prefix that [`Display`](fmt::Display) adds.
39    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
49/// Result alias used throughout the crate.
50pub type Result<T> = std::result::Result<T, Error>;
51
52/// Returns `Err(InvalidInput)` with a lazily built message unless `ok` holds.
53pub(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
61/// Index and value of the first non-finite entry, if any.
62pub(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
70/// `InvalidInput` unless every entry of `values` is finite.
71pub(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
78/// Rejects nonfinite intermediate arithmetic before it can disappear in a maximum.
79pub(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}