Skip to main content

rmath/bigint/
rat_err.rs

1use std::fmt::{Debug, Formatter, Result, Display};
2use std::error::Error;
3
4#[derive(Copy, Clone, Eq, PartialEq)]
5pub enum RatErrKind {
6    DenominatorIsZero,
7    NumeratorIsZero,
8    ParseStringWrong,
9}
10
11impl Debug for RatErrKind {
12    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
13        match self {
14            RatErrKind::DenominatorIsZero => {
15                write!(f, "{}", "DenominatorIsZero")
16            },
17            RatErrKind::NumeratorIsZero => {
18                write!(f, "{}", "NumeratorIsZero")
19            },
20            RatErrKind::ParseStringWrong => {
21                write!(f, "{}", "ParseStringWrong")
22            }
23        }
24    }
25}
26
27#[derive(Debug)]
28pub struct RatError {
29    kind: RatErrKind,
30    error: Option<Box<dyn Error + Send + Sync>>,
31}
32
33impl RatError {
34    pub fn new<E>(kind: RatErrKind, error: E) -> RatError 
35        where E: Into<Box<dyn Error + Sync + Send>> {
36        RatError {
37            kind,
38            error: Some(error.into()),
39        }
40    }
41    
42    pub fn kind(&self) -> RatErrKind {
43        self.kind
44    }
45}
46
47impl Display for RatError {
48    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
49        match self.error.as_ref() {
50            Some(x) => std::fmt::Display::fmt(x, f),
51            None => write!(f, "{:?}", self.kind),
52        }
53    }
54}
55
56impl Error for RatError {
57    fn source(&self) -> Option<&(dyn Error + 'static)> {
58        match self.error.as_ref() {
59            Some(x) => x.source(),
60            None => None
61        }
62    }
63}