Skip to main content

df_hyperliquid_core/utils/dec/
mod.rs

1//! Exact decimals for every amount the venue prices in: read from and written as the venue's strings,
2//! added, multiplied, divided and rounded, never through a float.
3
4mod arith;
5mod round;
6mod wire;
7
8pub use round::Round;
9pub use wire::BadDec;
10
11use std::cmp::Ordering;
12
13/// The finest figure this type keeps. The venue's own ceiling is eight
14/// places for a spot amount; marks, funding and ETH in wei run deeper.
15pub const MAX_SCALE: u32 = 18;
16
17/// An exact decimal, `units / 10^scale`, for every amount the venue prices
18/// in. The venue sends and takes these as strings, and a float between the
19/// two would change the figure that gets signed.
20#[derive(Debug, Clone, Copy, Default)]
21pub struct Dec {
22    units: i128,
23    scale: u32,
24}
25
26impl Dec {
27    /// 0.
28    pub const ZERO: Dec = Dec { units: 0, scale: 0 };
29    /// 1.
30    pub const ONE: Dec = Dec { units: 1, scale: 0 };
31
32    /// `units / 10^scale`. A scale past [`MAX_SCALE`] is refused, and so is
33    /// `i128::MIN`, which has no positive counterpart.
34    #[must_use]
35    pub const fn new(units: i128, scale: u32) -> Option<Dec> {
36        if scale > MAX_SCALE || units == i128::MIN {
37            return None;
38        }
39        Some(Dec { units, scale })
40    }
41
42    /// `units / 10^SCALE` for a figure written into the code: `Dec::lit::<2>(475)`
43    /// is 4.75. The scale is checked when the program is built, so a constant
44    /// needs no fallback; one past [`MAX_SCALE`] does not compile.
45    ///
46    /// ```compile_fail,E0080
47    /// const TOO_FINE: df_hyperliquid_core::utils::Dec = df_hyperliquid_core::utils::Dec::lit::<19>(1);
48    /// ```
49    #[must_use]
50    pub const fn lit<const SCALE: u32>(units: i128) -> Dec {
51        const { assert!(SCALE <= MAX_SCALE, "a Dec keeps at most eighteen places") };
52        Dec { units, scale: SCALE }
53    }
54
55    /// A whole number, with no places behind the point.
56    #[must_use]
57    pub const fn from_int(whole: i64) -> Dec {
58        Dec { units: whole as i128, scale: 0 }
59    }
60
61    /// `units` and `scale` as held, for the fuzz target that holds the two readers together.
62    #[cfg(fuzzing)]
63    pub(crate) const fn parts(self) -> (i128, u32) {
64        (self.units, self.scale)
65    }
66
67    /// The same value with no trailing zeros behind the point.
68    #[must_use]
69    fn normal(mut self) -> Dec {
70        while self.scale > 0 && self.units % 10 == 0 {
71            self.units /= 10;
72            self.scale -= 1;
73        }
74        if self.units == 0 {
75            self.scale = 0;
76        }
77        self
78    }
79
80    /// Whether the value is 0.
81    #[must_use]
82    pub const fn is_zero(self) -> bool {
83        self.units == 0
84    }
85
86    /// Whether the value is below 0.
87    #[must_use]
88    pub const fn is_negative(self) -> bool {
89        self.units < 0
90    }
91
92    /// Whether the value is above 0.
93    #[must_use]
94    pub const fn is_positive(self) -> bool {
95        self.units > 0
96    }
97
98    /// Whether the value has nothing behind the point once trailing zeros are dropped.
99    #[must_use]
100    pub fn is_integer(self) -> bool {
101        self.normal().scale == 0
102    }
103
104    /// How many places behind the point the value needs.
105    #[must_use]
106    pub fn places(self) -> u32 {
107        self.normal().scale
108    }
109
110    /// The value without its sign, at the same scale. Every constructor and
111    /// operation keeps `units` above `i128::MIN`, so this never overflows; the
112    /// saturating call only guards a value built with [`Dec::lit`] from `i128::MIN`.
113    #[must_use]
114    pub const fn abs(self) -> Dec {
115        Dec { units: self.units.saturating_abs(), scale: self.scale }
116    }
117
118    /// The value with its sign flipped, at the same scale. See [`Dec::abs`] for
119    /// why this never overflows.
120    #[must_use]
121    pub const fn negate(self) -> Dec {
122        Dec { units: self.units.saturating_neg(), scale: self.scale }
123    }
124
125    fn aligned(self, other: Dec) -> Option<(i128, i128, u32)> {
126        let scale = self.scale.max(other.scale);
127        Some((
128            self.units.checked_mul(ten(scale - self.scale)?)?,
129            other.units.checked_mul(ten(scale - other.scale)?)?,
130            scale,
131        ))
132    }
133}
134
135/// `10^power`, or `None` past what an `i128` holds.
136fn ten(power: u32) -> Option<i128> {
137    10i128.checked_pow(power)
138}
139
140impl PartialEq for Dec {
141    fn eq(&self, other: &Dec) -> bool {
142        self.cmp(other) == Ordering::Equal
143    }
144}
145
146impl Eq for Dec {}
147
148impl PartialOrd for Dec {
149    fn partial_cmp(&self, other: &Dec) -> Option<Ordering> {
150        Some(self.cmp(other))
151    }
152}
153
154impl Ord for Dec {
155    fn cmp(&self, other: &Dec) -> Ordering {
156        match self.aligned(*other) {
157            Some((a, b, _)) => a.cmp(&b),
158            // Only a figure near the i128 ceiling lands here; its sign and
159            // integer part decide it.
160            None => (self.units / ten(self.scale).unwrap_or(1)).cmp(&(other.units / ten(other.scale).unwrap_or(1))),
161        }
162    }
163}
164
165#[cfg(test)]
166#[path = "tests/dec.rs"]
167mod tests;