1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// #![allow(unaligned_references)]
use crate::prelude::*;
use borsh::BorshDeserialize;
use borsh::BorshSerialize;
use core::cmp::Ordering;
use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal;

#[derive(Default, Eq, PartialEq, Copy, Clone, BorshSerialize, BorshDeserialize)]
pub struct BorshDecimal {
    pub mantissa: i128,
    pub scale: u32,
}
impl From<Decimal> for BorshDecimal {
    fn from(s: Decimal) -> Self {
        Self {
            mantissa: s.mantissa(),
            scale: s.scale(),
        }
    }
}
impl From<&Decimal> for BorshDecimal {
    fn from(s: &Decimal) -> Self {
        Self {
            mantissa: s.mantissa(),
            scale: s.scale(),
        }
    }
}
impl From<SwitchboardDecimal> for BorshDecimal {
    fn from(s: SwitchboardDecimal) -> Self {
        Self {
            mantissa: s.mantissa,
            scale: s.scale,
        }
    }
}
impl From<BorshDecimal> for SwitchboardDecimal {
    fn from(val: BorshDecimal) -> Self {
        SwitchboardDecimal {
            mantissa: val.mantissa,
            scale: val.scale,
        }
    }
}
impl TryInto<Decimal> for &BorshDecimal {
    type Error = OnDemandError;
    fn try_into(self) -> std::result::Result<Decimal, OnDemandError> {
        Decimal::try_from_i128_with_scale(self.mantissa, self.scale)
            .map_err(|_| OnDemandError::DecimalConversionError)
    }
}

impl TryInto<Decimal> for BorshDecimal {
    type Error = OnDemandError;
    fn try_into(self) -> std::result::Result<Decimal, OnDemandError> {
        Decimal::try_from_i128_with_scale(self.mantissa, self.scale)
            .map_err(|_| OnDemandError::DecimalConversionError)
    }
}

#[repr(packed)]
#[derive(Default, Debug, Eq, PartialEq, BorshDeserialize)]
pub struct SwitchboardDecimal {
    /// The part of a floating-point number that represents the significant digits of that number, and that is multiplied by the base, 10, raised to the power of scale to give the actual value of the number.
    pub mantissa: i128,
    /// The number of decimal places to move to the left to yield the actual value.
    pub scale: u32,
}

impl SwitchboardDecimal {
    pub fn new(mantissa: i128, scale: u32) -> SwitchboardDecimal {
        Self { mantissa, scale }
    }
    pub fn from_rust_decimal(d: Decimal) -> SwitchboardDecimal {
        Self::new(d.mantissa(), d.scale())
    }
    pub fn from_f64(v: f64) -> SwitchboardDecimal {
        let dec = Decimal::from_f64(v).unwrap();
        Self::from_rust_decimal(dec)
    }
    pub fn scale_to(&self, new_scale: u32) -> i128 {
        match { self.scale }.cmp(&new_scale) {
            std::cmp::Ordering::Greater => self
                .mantissa
                .checked_div(10_i128.pow(self.scale - new_scale))
                .unwrap(),
            std::cmp::Ordering::Less => self
                .mantissa
                .checked_mul(10_i128.pow(new_scale - self.scale))
                .unwrap(),
            std::cmp::Ordering::Equal => self.mantissa,
        }
    }
    pub fn new_with_scale(&self, new_scale: u32) -> Self {
        let mantissa = self.scale_to(new_scale);
        SwitchboardDecimal {
            mantissa,
            scale: new_scale,
        }
    }
}
impl From<Decimal> for SwitchboardDecimal {
    fn from(val: Decimal) -> Self {
        SwitchboardDecimal::new(val.mantissa(), val.scale())
    }
}
impl TryInto<Decimal> for &SwitchboardDecimal {
    type Error = OnDemandError;
    fn try_into(self) -> std::result::Result<Decimal, OnDemandError> {
        Decimal::try_from_i128_with_scale(self.mantissa, self.scale)
            .map_err(|_| OnDemandError::DecimalConversionError)
    }
}

impl TryInto<Decimal> for SwitchboardDecimal {
    type Error = OnDemandError;
    fn try_into(self) -> std::result::Result<Decimal, OnDemandError> {
        Decimal::try_from_i128_with_scale(self.mantissa, self.scale)
            .map_err(|_| OnDemandError::DecimalConversionError)
    }
}

impl Ord for SwitchboardDecimal {
    fn cmp(&self, other: &Self) -> Ordering {
        let s: Decimal = self.try_into().unwrap();
        let other: Decimal = other.try_into().unwrap();
        s.cmp(&other)
    }
}

impl PartialOrd for SwitchboardDecimal {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
    fn lt(&self, other: &Self) -> bool {
        let s: Decimal = self.try_into().unwrap();
        let other: Decimal = other.try_into().unwrap();
        s < other
    }
    fn le(&self, other: &Self) -> bool {
        let s: Decimal = self.try_into().unwrap();
        let other: Decimal = other.try_into().unwrap();
        s <= other
    }
    fn gt(&self, other: &Self) -> bool {
        let s: Decimal = self.try_into().unwrap();
        let other: Decimal = other.try_into().unwrap();
        s > other
    }
    fn ge(&self, other: &Self) -> bool {
        let s: Decimal = self.try_into().unwrap();
        let other: Decimal = other.try_into().unwrap();
        s >= other
    }
}

impl From<SwitchboardDecimal> for bool {
    fn from(s: SwitchboardDecimal) -> Self {
        let dec: Decimal = (&s).try_into().unwrap();
        dec.round().mantissa() != 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn switchboard_decimal_into_rust_decimal() {
        let swb_decimal = &SwitchboardDecimal {
            mantissa: 12345,
            scale: 2,
        };
        let decimal: Decimal = swb_decimal.try_into().unwrap();
        assert_eq!(decimal.mantissa(), 12345);
        assert_eq!(decimal.scale(), 2);
    }

    #[test]
    fn empty_switchboard_decimal_is_false() {
        let swb_decimal = SwitchboardDecimal {
            mantissa: 0,
            scale: 0,
        };
        let b: bool = swb_decimal.into();
        assert!(!b);
        let swb_decimal_neg = SwitchboardDecimal {
            mantissa: -0,
            scale: 0,
        };
        let b: bool = swb_decimal_neg.into();
        assert!(!b);
    }

    // #[test]
    // fn switchboard_decimal_to_u64() {
    // // 1234.5678
    // let swb_decimal = SwitchboardDecimal {
    // mantissa: 12345678,
    // scale: 4,
    // };
    // let b: u64 = swb_decimal.try_into().unwrap();
    // assert_eq!(b, 1234);
    // }
    //
    // #[test]
    // fn switchboard_decimal_to_f64() {
    // // 1234.5678
    // let swb_decimal = SwitchboardDecimal {
    // mantissa: 12345678,
    // scale: 4,
    // };
    // let b: f64 = swb_decimal.try_into().unwrap();
    // assert_eq!(b, 1234.5678);
    //
    // let swb_f64 = SwitchboardDecimal::from_f64(1234.5678);
    // assert_eq!(swb_decimal, swb_f64);
    // }
}