use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Error {
NotFinite {
input: Input,
value: f64,
},
NotPositive {
input: Input,
value: f64,
},
Negative {
input: Input,
value: f64,
},
ProbabilityOutOfRange {
value: f64,
},
Overflow {
quantity: &'static str,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Input {
Spot,
Strike,
Rate,
CostOfCarry,
Volatility,
Time,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotFinite { input, value } => {
write!(f, "{input} must be a finite number, got {value}")
}
Self::NotPositive { input, value } => {
write!(f, "{input} must be greater than zero, got {value}")
}
Self::Negative { input, value } => {
write!(f, "{input} must be zero or greater, got {value}")
}
Self::ProbabilityOutOfRange { value } => {
write!(
f,
"probability must be strictly between 0 and 1, got {value}"
)
}
Self::Overflow { quantity } => write!(
f,
"{quantity} is not a finite f64; check the input magnitudes and units \
(prices in one currency, rates as annual decimals such as 0.05, \
time in years)"
),
}
}
}
impl std::error::Error for Error {}
impl fmt::Display for Input {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Spot => "spot",
Self::Strike => "strike",
Self::Rate => "rate",
Self::CostOfCarry => "cost of carry",
Self::Volatility => "volatility",
Self::Time => "time",
})
}
}
pub(crate) fn finite(input: Input, value: f64) -> Result<f64, Error> {
if value.is_finite() {
Ok(value)
} else {
Err(Error::NotFinite { input, value })
}
}
pub(crate) fn positive(input: Input, value: f64) -> Result<f64, Error> {
if finite(input, value)? > 0.0 {
Ok(value)
} else {
Err(Error::NotPositive { input, value })
}
}
pub(crate) fn non_negative(input: Input, value: f64) -> Result<f64, Error> {
if finite(input, value)? >= 0.0 {
Ok(value)
} else {
Err(Error::Negative { input, value })
}
}