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 #[must_use]
63 fn normal(mut self) -> Dec {
64 while self.scale > 0 && self.units % 10 == 0 {
65 self.units /= 10;
66 self.scale -= 1;
67 }
68 if self.units == 0 {
69 self.scale = 0;
70 }
71 self
72 }
73
74 #[must_use]
76 pub const fn is_zero(self) -> bool {
77 self.units == 0
78 }
79
80 #[must_use]
82 pub const fn is_negative(self) -> bool {
83 self.units < 0
84 }
85
86 #[must_use]
88 pub const fn is_positive(self) -> bool {
89 self.units > 0
90 }
91
92 #[must_use]
94 pub fn is_integer(self) -> bool {
95 self.normal().scale == 0
96 }
97
98 #[must_use]
100 pub fn places(self) -> u32 {
101 self.normal().scale
102 }
103
104 #[must_use]
108 pub const fn abs(self) -> Dec {
109 Dec { units: self.units.saturating_abs(), scale: self.scale }
110 }
111
112 #[must_use]
115 pub const fn negate(self) -> Dec {
116 Dec { units: self.units.saturating_neg(), scale: self.scale }
117 }
118
119 fn aligned(self, other: Dec) -> Option<(i128, i128, u32)> {
120 let scale = self.scale.max(other.scale);
121 Some((
122 self.units.checked_mul(ten(scale - self.scale)?)?,
123 other.units.checked_mul(ten(scale - other.scale)?)?,
124 scale,
125 ))
126 }
127}
128
129fn ten(power: u32) -> Option<i128> {
131 10i128.checked_pow(power)
132}
133
134impl PartialEq for Dec {
135 fn eq(&self, other: &Dec) -> bool {
136 self.cmp(other) == Ordering::Equal
137 }
138}
139
140impl Eq for Dec {}
141
142impl PartialOrd for Dec {
143 fn partial_cmp(&self, other: &Dec) -> Option<Ordering> {
144 Some(self.cmp(other))
145 }
146}
147
148impl Ord for Dec {
149 fn cmp(&self, other: &Dec) -> Ordering {
150 match self.aligned(*other) {
151 Some((a, b, _)) => a.cmp(&b),
152 None => (self.units / ten(self.scale).unwrap_or(1)).cmp(&(other.units / ten(other.scale).unwrap_or(1))),
155 }
156 }
157}
158
159#[cfg(test)]
160#[path = "tests/dec.rs"]
161mod tests;