rust_finprim/
error.rs

1use core::fmt::{self, Debug, Display};
2
3/// Root finding general errors
4#[derive(Debug, Copy, Clone, PartialEq)]
5pub enum RootFindingError<T> {
6    /// Error when the method fails to converge
7    FailedToConverge { last_x: T, last_fx: T },
8    /// Error when the method attempts to divide by zero
9    DivideByZero { last_x: T, last_fx: T },
10    /// Error when the bracket provided is invalid
11    InvalidBracket,
12}
13
14impl<T: Display> Display for RootFindingError<T> {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        match self {
17            RootFindingError::FailedToConverge { last_x, last_fx } => {
18                write!(f, "Failed to converge. Last x: {}, Last f(x): {}", last_x, last_fx)
19            }
20            RootFindingError::DivideByZero { last_x, last_fx } => {
21                write!(
22                    f,
23                    "Attempted to divide by zero. Last x: {}, Last f(x): {}",
24                    last_x, last_fx
25                )
26            }
27            RootFindingError::InvalidBracket => write!(f, "Invalid bracket provided."),
28        }
29    }
30}
31#[cfg(feature = "std")]
32impl<T: Display + Debug> std::error::Error for RootFindingError<T> {}
33
34/// Custom error type for financial calculations in FinPrim
35#[derive(Debug, Copy, Clone, PartialEq)]
36pub enum FinPrimError<T> {
37    /// Divide by zero error
38    DivideByZero,
39    /// The method failed to find a root
40    RootFindingError(RootFindingError<T>),
41}
42
43impl<T: Display> Display for FinPrimError<T> {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            FinPrimError::DivideByZero => write!(f, "Division by zero error."),
47            FinPrimError::RootFindingError(e) => write!(f, "Root finding error: {}", e),
48        }
49    }
50}
51
52#[cfg(feature = "std")]
53impl<T: Display + Debug> std::error::Error for FinPrimError<T> {}