df_hyperliquid_core/utils/dec/
mod.rs1mod arith;
5mod round;
6mod wire;
7
8pub use round::Round;
9pub use wire::BadDec;
10
11use std::cmp::Ordering;
12
13pub const MAX_SCALE: u32 = 18;
16
17#[derive(Debug, Clone, Copy, Default)]
21pub struct Dec {
22 units: i128,
23 scale: u32,
24}
25
26impl Dec {
27 pub const ZERO: Dec = Dec { units: 0, scale: 0 };
29 pub const ONE: Dec = Dec { units: 1, scale: 0 };
31
32 #[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 #[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 #[must_use]
57 pub const fn from_int(whole: i64) -> Dec {
58 Dec { units: whole as i128, scale: 0 }
59 }
60
61 #[cfg(fuzzing)]
63 pub(crate) const fn parts(self) -> (i128, u32) {
64 (self.units, self.scale)
65 }
66
67 #[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 #[must_use]
82 pub const fn is_zero(self) -> bool {
83 self.units == 0
84 }
85
86 #[must_use]
88 pub const fn is_negative(self) -> bool {
89 self.units < 0
90 }
91
92 #[must_use]
94 pub const fn is_positive(self) -> bool {
95 self.units > 0
96 }
97
98 #[must_use]
100 pub fn is_integer(self) -> bool {
101 self.normal().scale == 0
102 }
103
104 #[must_use]
106 pub fn places(self) -> u32 {
107 self.normal().scale
108 }
109
110 #[must_use]
114 pub const fn abs(self) -> Dec {
115 Dec { units: self.units.saturating_abs(), scale: self.scale }
116 }
117
118 #[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
135fn 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 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;