df_hyperliquid_core/utils/dec/
wire.rs1use std::{fmt, str::FromStr};
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
7
8use crate::utils::dec::{Dec, MAX_SCALE};
9
10#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
12#[non_exhaustive]
13pub enum BadDec {
14 #[error("`{0}` is not a decimal number")]
17 NotANumber(String),
18 #[error("`{0}` has more than eighteen decimal places")]
20 TooFine(String),
21 #[error("`{0}` is larger than this build can count")]
23 OutOfRange(String),
24}
25
26impl Dec {
27 pub fn parse(text: &str) -> Result<Dec, BadDec> {
30 match Dec::parse_short(text.as_bytes()) {
31 Some(dec) => Ok(dec),
32 None => Dec::parse_long(text),
33 }
34 }
35
36 pub(crate) fn parse_short(text: &[u8]) -> Option<Dec> {
41 let (negative, body) = match text.split_first() {
42 Some((b'-', rest)) => (true, rest),
43 _ => (false, text),
44 };
45 if body.len() > 19 {
46 return None;
47 }
48 let mut units: u64 = 0;
49 let mut point: Option<usize> = None;
50 for (at, &byte) in body.iter().enumerate() {
51 match byte {
52 b'0'..=b'9' => units = units * 10 + u64::from(byte - b'0'),
53 b'.' if point.is_none() => point = Some(at),
54 _ => return None,
55 }
56 }
57 let digits = body.len() - usize::from(point.is_some());
58 if digits == 0 {
59 return None;
60 }
61 let mut scale = point.map_or(0, |at| (body.len() - at - 1) as u32);
63 while scale > 0 && units.is_multiple_of(10) {
64 units /= 10;
65 scale -= 1;
66 }
67 if units == 0 {
68 scale = 0;
69 }
70 let units = i128::from(units);
71 Some(Dec { units: if negative { -units } else { units }, scale })
72 }
73
74 pub(crate) fn parse_long(text: &str) -> Result<Dec, BadDec> {
76 let bad = || BadDec::NotANumber(text.to_owned());
77 let body = text.trim();
78 let (negative, body) = match body.strip_prefix('-') {
79 Some(rest) => (true, rest),
80 None => (false, body.strip_prefix('+').unwrap_or(body)),
81 };
82 let (whole, fraction) = body.split_once('.').unwrap_or((body, ""));
83 if whole.is_empty() && fraction.is_empty() {
84 return Err(bad());
85 }
86 if !whole.bytes().all(|b| b.is_ascii_digit()) || !fraction.bytes().all(|b| b.is_ascii_digit()) {
87 return Err(bad());
88 }
89 let fraction = fraction.trim_end_matches('0');
90 let scale = u32::try_from(fraction.len()).map_err(|_| BadDec::TooFine(text.to_owned()))?;
91 if scale > MAX_SCALE {
92 return Err(BadDec::TooFine(text.to_owned()));
93 }
94 let mut units: i128 = 0;
95 for digit in whole.bytes().chain(fraction.bytes()) {
96 units = units
97 .checked_mul(10)
98 .and_then(|u| u.checked_add(i128::from(digit - b'0')))
99 .ok_or_else(|| BadDec::OutOfRange(text.to_owned()))?;
100 }
101 Ok(Dec { units: if negative { -units } else { units }, scale }.normal())
102 }
103
104 #[must_use]
107 pub fn to_wire(self) -> String {
108 self.to_string()
109 }
110}
111
112impl fmt::Display for Dec {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 let normal = self.normal();
115 let sign = if normal.units < 0 { "-" } else { "" };
116 let magnitude = normal.units.unsigned_abs();
117 if normal.scale == 0 {
118 return write!(f, "{sign}{magnitude}");
119 }
120 let step = 10u128.pow(normal.scale);
121 let places = normal.scale as usize;
122 write!(f, "{sign}{}.{:0places$}", magnitude / step, magnitude % step)
123 }
124}
125
126impl FromStr for Dec {
127 type Err = BadDec;
128
129 fn from_str(text: &str) -> Result<Self, Self::Err> {
130 Dec::parse(text)
131 }
132}
133
134impl Serialize for Dec {
135 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
136 serializer.collect_str(self)
137 }
138}
139
140impl<'de> Deserialize<'de> for Dec {
143 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
144 struct Visitor;
145
146 impl de::Visitor<'_> for Visitor {
147 type Value = Dec;
148
149 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.write_str("a decimal string or an integer")
151 }
152
153 fn visit_str<E: de::Error>(self, text: &str) -> Result<Dec, E> {
154 Dec::parse(text).map_err(E::custom)
155 }
156
157 fn visit_u64<E: de::Error>(self, value: u64) -> Result<Dec, E> {
158 Ok(Dec { units: i128::from(value), scale: 0 })
159 }
160
161 fn visit_i64<E: de::Error>(self, value: i64) -> Result<Dec, E> {
162 Ok(Dec { units: i128::from(value), scale: 0 })
163 }
164 }
165
166 deserializer.deserialize_any(Visitor)
167 }
168}
169
170#[cfg(test)]
171#[path = "tests/wire.rs"]
172mod tests;