Skip to main content

df_hyperliquid_core/utils/dec/
arith.rs

1//! Arithmetic on decimals: a sum or a difference exact, a product exact to eighteen places, a
2//! quotient kept to the places asked, and `None` where a figure would pass what a `Dec` holds.
3
4use crate::utils::dec::round::{Round, divide};
5use crate::utils::dec::{Dec, MAX_SCALE, ten};
6
7impl Dec {
8    /// `self + other`, exact. `None` when the sum passes what a `Dec` holds.
9    #[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    /// `self - other`, exact. `None` when the difference passes what a `Dec` holds.
16    #[must_use]
17    pub fn checked_sub(self, other: Dec) -> Option<Dec> {
18        self.checked_add(other.negate())
19    }
20
21    /// Every figure added exactly, in order; zero for none. `None` once a
22    /// running total passes what a `Dec` holds.
23    #[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    /// Exact while the product fits eighteen places; past that, the nearest.
29    #[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    /// `self / other` kept to `places` behind the point.
42    #[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        // At one scale a/b is a division of integers. Its digits behind the
49        // point come one at a time from the remainder, which stays below the
50        // divisor, so nothing grows past the quotient itself (scaling the
51        // numerator up front would overflow for figures in the hundreds of
52        // millions at ten places).
53        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
76/// `units`, or `None` for `i128::MIN`: a `Dec` never holds it, so its sign can always be flipped.
77fn kept(units: i128) -> Option<i128> {
78    (units != i128::MIN).then_some(units)
79}
80
81#[cfg(test)]
82#[path = "tests/arith.rs"]
83mod tests;