df_hyperliquid_core/utils/dec/
arith.rs1use crate::utils::dec::round::{Round, divide};
5use crate::utils::dec::{Dec, MAX_SCALE, ten};
6
7impl Dec {
8 #[must_use]
10 pub fn checked_add(self, other: Dec) -> Option<Dec> {
11 let (a, b, scale) = self.aligned(other)?;
12 Some(Dec { units: kept(a.checked_add(b)?)?, scale }.normal())
13 }
14
15 #[must_use]
17 pub fn checked_sub(self, other: Dec) -> Option<Dec> {
18 self.checked_add(other.negate())
19 }
20
21 #[must_use]
24 pub fn checked_sum(figures: impl IntoIterator<Item = Dec>) -> Option<Dec> {
25 figures.into_iter().try_fold(Dec::ZERO, Dec::checked_add)
26 }
27
28 #[must_use]
30 pub fn checked_mul(self, other: Dec) -> Option<Dec> {
31 let (a, b) = (self.normal(), other.normal());
32 let units = kept(a.units.checked_mul(b.units)?)?;
33 let scale = a.scale + b.scale;
34 if scale <= MAX_SCALE {
35 return Some(Dec { units, scale }.normal());
36 }
37 let units = divide(units, ten(scale - MAX_SCALE)?, Round::Nearest);
38 Some(Dec { units, scale: MAX_SCALE }.normal())
39 }
40
41 #[must_use]
43 pub fn checked_div(self, other: Dec, places: u32, round: Round) -> Option<Dec> {
44 if other.units == 0 || places > MAX_SCALE {
45 return None;
46 }
47 let (a, b) = (self.normal(), other.normal());
48 let scale = a.scale.max(b.scale);
54 let top = a.units.checked_mul(ten(scale - a.scale)?)?;
55 let bottom = b.units.checked_mul(ten(scale - b.scale)?)?;
56 let negative = (top < 0) != (bottom < 0);
57 let (top, bottom) = (top.unsigned_abs(), bottom.unsigned_abs());
58 let mut units = top / bottom;
59 let mut rest = top % bottom;
60 for _ in 0..places {
61 rest = rest.checked_mul(10)?;
62 units = units.checked_mul(10)?.checked_add(rest / bottom)?;
63 rest %= bottom;
64 }
65 let away = match round {
66 Round::Down => false,
67 Round::Up => rest != 0,
68 Round::Nearest => rest != 0 && rest >= bottom - rest,
69 };
70 let units = i128::try_from(units.checked_add(u128::from(away))?).ok()?;
71 let units = if negative { -units } else { units };
72 Some(Dec { units, scale: places }.normal())
73 }
74}
75
76fn kept(units: i128) -> Option<i128> {
78 (units != i128::MIN).then_some(units)
79}
80
81#[cfg(test)]
82#[path = "tests/arith.rs"]
83mod tests;