1use std::fmt;
5
6#[derive(Debug, Clone, Copy, PartialEq)]
11#[non_exhaustive]
12pub enum Error {
13 NotFinite {
15 input: Input,
17 value: f64,
19 },
20 NotPositive {
22 input: Input,
24 value: f64,
26 },
27 Negative {
29 input: Input,
31 value: f64,
33 },
34 ProbabilityOutOfRange {
36 value: f64,
38 },
39 Overflow {
43 quantity: &'static str,
45 },
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51pub enum Input {
52 Spot,
54 Strike,
56 Rate,
58 CostOfCarry,
60 Volatility,
62 Time,
64}
65
66impl fmt::Display for Error {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 match self {
69 Self::NotFinite { input, value } => {
70 write!(f, "{input} must be a finite number, got {value}")
71 }
72 Self::NotPositive { input, value } => {
73 write!(f, "{input} must be greater than zero, got {value}")
74 }
75 Self::Negative { input, value } => {
76 write!(f, "{input} must be zero or greater, got {value}")
77 }
78 Self::ProbabilityOutOfRange { value } => {
79 write!(
80 f,
81 "probability must be strictly between 0 and 1, got {value}"
82 )
83 }
84 Self::Overflow { quantity } => write!(
85 f,
86 "{quantity} is not a finite f64; check the input magnitudes and units \
87 (prices in one currency, rates as annual decimals such as 0.05, \
88 time in years)"
89 ),
90 }
91 }
92}
93
94impl std::error::Error for Error {}
95
96impl fmt::Display for Input {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 f.write_str(match self {
99 Self::Spot => "spot",
100 Self::Strike => "strike",
101 Self::Rate => "rate",
102 Self::CostOfCarry => "cost of carry",
103 Self::Volatility => "volatility",
104 Self::Time => "time",
105 })
106 }
107}
108
109pub(crate) fn finite(input: Input, value: f64) -> Result<f64, Error> {
111 if value.is_finite() {
112 Ok(value)
113 } else {
114 Err(Error::NotFinite { input, value })
115 }
116}
117
118pub(crate) fn positive(input: Input, value: f64) -> Result<f64, Error> {
120 if finite(input, value)? > 0.0 {
121 Ok(value)
122 } else {
123 Err(Error::NotPositive { input, value })
124 }
125}
126
127pub(crate) fn non_negative(input: Input, value: f64) -> Result<f64, Error> {
129 if finite(input, value)? >= 0.0 {
130 Ok(value)
131 } else {
132 Err(Error::Negative { input, value })
133 }
134}