ledger_models/fintekkers/wrappers/models/utils/
decimal.rs

1use crate::fintekkers::models::util::DecimalValueProto;
2use crate::fintekkers::wrappers::models::utils::errors::Error;
3
4use rust_decimal::Decimal;
5use std::fmt;
6
7pub struct DecimalWrapper {
8    proto: DecimalValueProto,
9}
10
11impl AsRef<DecimalValueProto> for DecimalWrapper {
12    fn as_ref(&self) -> &DecimalValueProto {
13        &self.proto
14    }
15}
16
17impl DecimalWrapper {
18    pub fn new(proto: DecimalValueProto) -> Self {
19        DecimalWrapper { proto }
20    }
21}
22
23impl From<&str> for DecimalWrapper {
24    fn from(value: &str) -> Self {
25        DecimalWrapper {
26            proto: DecimalValueProto {
27                arbitrary_precision_value: value.to_owned(),
28            },
29        }
30    }
31}
32impl From<&Decimal> for DecimalWrapper {
33    fn from(value: &Decimal) -> Self {
34        DecimalWrapper {
35            proto: DecimalValueProto {
36                arbitrary_precision_value: value.to_string(),
37            },
38        }
39    }
40}
41
42impl From<Decimal> for DecimalWrapper {
43    fn from(value: Decimal) -> Self {
44        DecimalWrapper {
45            proto: DecimalValueProto {
46                arbitrary_precision_value: value.to_string(),
47            },
48        }
49    }
50}
51
52impl TryFrom<DecimalWrapper> for Decimal {
53    type Error = Error;
54
55    fn try_from(value: DecimalWrapper) -> Result<Self, Error> {
56        let str:&str = &value.proto.arbitrary_precision_value;
57
58        match Decimal::try_from(str) {
59                Ok(v) => Ok(v),
60                Err(_result) => Err(Error::DecimalConversion)
61        }
62    }
63}
64
65
66impl fmt::Display for DecimalWrapper {
67    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
68        fmt.write_str(&self.proto.arbitrary_precision_value.to_string())?;
69        Ok(())
70    }
71}
72
73#[cfg(test)]
74mod test {
75    use super::*;
76
77    #[test]
78    fn test_proto_to_decimal() {
79        let input = DecimalWrapper {
80            proto: DecimalValueProto {
81                arbitrary_precision_value: String::from("1234567.89"),
82            },
83        };
84
85        let output: Decimal = input.try_into().unwrap();
86
87        assert_eq!(output.to_string(), "1234567.89");
88    }
89
90    #[test]
91    fn test_decimal_to_proto() {
92        let input = Decimal::from_i128_with_scale(123456789, 2);
93        let output = DecimalWrapper::from(&input);
94
95        assert_eq!(output.proto.arbitrary_precision_value, "1234567.89");
96    }
97}