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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use std::{
    fmt::Display,
    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign},
};

use candid::{CandidType, Nat};
use num_bigint::BigUint;
use serde::Deserialize;

use crate::{d::EDs, ES_BASES};

pub type E8s = ECs<8>;

/// Fixed-point decimals with primitive math (+-*/) implemented correctly
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
pub struct ECs<const DECIMALS: usize> {
    pub val: BigUint,
}

impl<const D: usize> ECs<D> {
    pub fn new(val: BigUint) -> Self {
        Self { val }
    }

    pub fn base() -> &'static BigUint {
        if D > 31 {
            unreachable!("Decimal points after 31 are not supported");
        }

        // SAFETY: already checked
        unsafe { ES_BASES.get(D).unwrap_unchecked() }
    }

    pub fn base_d(decimals: u8) -> &'static BigUint {
        if decimals > 31 {
            unreachable!("Decimal points after 31 are not supported");
        }

        // SAFETY: already checked
        unsafe { ES_BASES.get(decimals as usize).unwrap_unchecked() }
    }

    pub fn zero() -> Self {
        Self::new(BigUint::ZERO)
    }

    pub fn one() -> Self {
        Self {
            val: Self::base().clone(),
        }
    }

    pub fn f0_1() -> Self {
        Self::new(Self::base() / BigUint::from(10u64))
    }

    pub fn f0_2() -> Self {
        Self::new(Self::base() / BigUint::from(5u64))
    }

    pub fn f0_25() -> Self {
        Self::new(Self::base() / BigUint::from(4u64))
    }

    pub fn f0_3() -> Self {
        Self::new(Self::base() * BigUint::from(3u64) / BigUint::from(10u64))
    }

    pub fn f0_33() -> Self {
        Self::new(Self::base() / BigUint::from(3u64))
    }

    pub fn f0_4() -> Self {
        Self::new(Self::base() * BigUint::from(2u64) / BigUint::from(5u64))
    }

    pub fn f0_5() -> Self {
        Self::new(Self::base() / BigUint::from(2u64))
    }

    pub fn f0_6() -> Self {
        Self::new(Self::base() * BigUint::from(3u64) / BigUint::from(5u64))
    }

    pub fn f0_67() -> Self {
        Self::new(Self::base() * BigUint::from(2u64) / BigUint::from(3u64))
    }

    pub fn f0_7() -> Self {
        Self::new(Self::base() * BigUint::from(7u64) / BigUint::from(10u64))
    }

    pub fn f0_75() -> Self {
        Self::new(Self::base() * BigUint::from(3u64) / BigUint::from(4u64))
    }

    pub fn f0_8() -> Self {
        Self::new(Self::base() * BigUint::from(4u64) / BigUint::from(5u64))
    }

    pub fn f0_9() -> Self {
        Self::new(Self::base() * BigUint::from(9u64) / BigUint::from(10u64))
    }

    pub fn two() -> Self {
        Self::new(Self::base() * BigUint::from(2u64))
    }

    pub fn sqrt(&self) -> Self {
        let base = Self::base();
        let whole = &self.val / base;
        let sqrt_whole = whole.sqrt();

        Self::new(sqrt_whole * base)
    }

    pub fn to_dynamic(self) -> EDs {
        EDs::new(self.val, D as u8)
    }

    pub fn to_decimals<const D1: usize>(self) -> ECs<D1> {
        if D1 == D {
            return ECs::<D1>::new(self.val);
        }

        let (dif, mul) = if D > D1 {
            (D - D1, false)
        } else {
            (D1 - D, true)
        };

        let base = Self::base_d(dif as u8);

        if mul {
            ECs::<D1>::new(self.val * base)
        } else {
            ECs::<D1>::new(self.val / base)
        }
    }
}

impl<const D: usize> Display for ECs<D> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let base = ECs::<D>::base();

        f.write_str(&format!("{}.{}", &self.val / base, &self.val % base))
    }
}

impl<const D: usize> Add for &ECs<D> {
    type Output = ECs<D>;

    fn add(self, rhs: Self) -> Self::Output {
        ECs::<D>::new(&self.val + &rhs.val)
    }
}

impl<const D: usize> Add for ECs<D> {
    type Output = ECs<D>;

    fn add(self, rhs: Self) -> Self::Output {
        (&self).add(&rhs)
    }
}

impl<const D: usize> Add<&ECs<D>> for ECs<D> {
    type Output = ECs<D>;

    fn add(self, rhs: &ECs<D>) -> Self::Output {
        (&self).add(rhs)
    }
}

impl<const D: usize> Add<ECs<D>> for &ECs<D> {
    type Output = ECs<D>;

    fn add(self, rhs: ECs<D>) -> Self::Output {
        self.add(&rhs)
    }
}

impl<const D: usize> AddAssign<&ECs<D>> for ECs<D> {
    fn add_assign(&mut self, rhs: &ECs<D>) {
        self.val.add_assign(&rhs.val)
    }
}

impl<const D: usize> AddAssign for ECs<D> {
    fn add_assign(&mut self, rhs: Self) {
        self.add_assign(&rhs)
    }
}

impl<const D: usize> Sub for &ECs<D> {
    type Output = ECs<D>;

    fn sub(self, rhs: Self) -> Self::Output {
        ECs::<D>::new(&self.val - &rhs.val)
    }
}

impl<const D: usize> Sub for ECs<D> {
    type Output = ECs<D>;

    fn sub(self, rhs: Self) -> Self::Output {
        (&self).sub(&rhs)
    }
}

impl<const D: usize> Sub<&ECs<D>> for ECs<D> {
    type Output = ECs<D>;

    fn sub(self, rhs: &ECs<D>) -> Self::Output {
        (&self).sub(rhs)
    }
}

impl<const D: usize> Sub<ECs<D>> for &ECs<D> {
    type Output = ECs<D>;

    fn sub(self, rhs: ECs<D>) -> Self::Output {
        self.sub(&rhs)
    }
}

impl<const D: usize> SubAssign<&ECs<D>> for ECs<D> {
    fn sub_assign(&mut self, rhs: &ECs<D>) {
        self.val.sub_assign(&rhs.val)
    }
}

impl<const D: usize> SubAssign for ECs<D> {
    fn sub_assign(&mut self, rhs: Self) {
        self.sub_assign(&rhs)
    }
}

impl<const D: usize> Mul for &ECs<D> {
    type Output = ECs<D>;

    fn mul(self, rhs: Self) -> Self::Output {
        ECs::<D>::new(&self.val * &rhs.val / ECs::<D>::base())
    }
}

impl<const D: usize> Mul for ECs<D> {
    type Output = ECs<D>;

    fn mul(self, rhs: Self) -> Self::Output {
        (&self).mul(&rhs)
    }
}

impl<const D: usize> Mul<&ECs<D>> for ECs<D> {
    type Output = ECs<D>;

    fn mul(self, rhs: &ECs<D>) -> Self::Output {
        (&self).mul(rhs)
    }
}

impl<const D: usize> Mul<ECs<D>> for &ECs<D> {
    type Output = ECs<D>;

    fn mul(self, rhs: ECs<D>) -> Self::Output {
        self.mul(&rhs)
    }
}

impl<const D: usize> MulAssign<&ECs<D>> for ECs<D> {
    fn mul_assign(&mut self, rhs: &ECs<D>) {
        self.val = &self.val * &rhs.val / ECs::<D>::base()
    }
}

impl<const D: usize> MulAssign for ECs<D> {
    fn mul_assign(&mut self, rhs: Self) {
        self.mul_assign(&rhs)
    }
}

impl<const D: usize> Div for &ECs<D> {
    type Output = ECs<D>;

    fn div(self, rhs: Self) -> Self::Output {
        ECs::<D>::new(&self.val * ECs::<D>::base() / &rhs.val)
    }
}

impl<const D: usize> Div for ECs<D> {
    type Output = ECs<D>;

    fn div(self, rhs: Self) -> Self::Output {
        (&self).div(&rhs)
    }
}

impl<const D: usize> Div<&ECs<D>> for ECs<D> {
    type Output = ECs<D>;

    fn div(self, rhs: &ECs<D>) -> Self::Output {
        (&self).div(rhs)
    }
}

impl<const D: usize> Div<ECs<D>> for &ECs<D> {
    type Output = ECs<D>;

    fn div(self, rhs: ECs<D>) -> Self::Output {
        self.div(&rhs)
    }
}

impl<const D: usize> DivAssign<&ECs<D>> for ECs<D> {
    fn div_assign(&mut self, rhs: &ECs<D>) {
        self.val = &self.val * ECs::<D>::base() / &rhs.val;
    }
}

impl<const D: usize> DivAssign for ECs<D> {
    fn div_assign(&mut self, rhs: Self) {
        self.div_assign(&rhs)
    }
}

impl<const D: usize> CandidType for ECs<D> {
    fn _ty() -> candid::types::Type {
        Nat::_ty()
    }

    fn idl_serialize<S>(&self, serializer: S) -> Result<(), S::Error>
    where
        S: candid::types::Serializer,
    {
        Nat::idl_serialize(&Nat(self.val.clone()), serializer)
    }
}

impl<'de, const C: usize> Deserialize<'de> for ECs<C> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(ECs::new(Nat::deserialize(deserializer)?.0))
    }
}

impl<const D: usize> From<u64> for ECs<D> {
    fn from(value: u64) -> Self {
        Self::new(BigUint::from(value))
    }
}

impl<const D: usize> From<u128> for ECs<D> {
    fn from(value: u128) -> Self {
        Self::new(BigUint::from(value))
    }
}