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)]
12pub enum BadDec {
13 #[error("`{0}` is not a decimal number")]
16 NotANumber(String),
17 #[error("`{0}` has more than eighteen decimal places")]
19 TooFine(String),
20 #[error("`{0}` is larger than this build can count")]
22 OutOfRange(String),
23}
24
25impl Dec {
26 pub fn parse(text: &str) -> Result<Dec, BadDec> {
29 let bad = || BadDec::NotANumber(text.to_owned());
30 let body = text.trim();
31 let (negative, body) = match body.strip_prefix('-') {
32 Some(rest) => (true, rest),
33 None => (false, body.strip_prefix('+').unwrap_or(body)),
34 };
35 let (whole, fraction) = body.split_once('.').unwrap_or((body, ""));
36 if whole.is_empty() && fraction.is_empty() {
37 return Err(bad());
38 }
39 if !whole.bytes().all(|b| b.is_ascii_digit()) || !fraction.bytes().all(|b| b.is_ascii_digit()) {
40 return Err(bad());
41 }
42 let fraction = fraction.trim_end_matches('0');
43 let scale = u32::try_from(fraction.len()).map_err(|_| BadDec::TooFine(text.to_owned()))?;
44 if scale > MAX_SCALE {
45 return Err(BadDec::TooFine(text.to_owned()));
46 }
47 let mut units: i128 = 0;
48 for digit in whole.bytes().chain(fraction.bytes()) {
49 units = units
50 .checked_mul(10)
51 .and_then(|u| u.checked_add(i128::from(digit - b'0')))
52 .ok_or_else(|| BadDec::OutOfRange(text.to_owned()))?;
53 }
54 Ok(Dec { units: if negative { -units } else { units }, scale }.normal())
55 }
56
57 #[must_use]
60 pub fn to_wire(self) -> String {
61 self.to_string()
62 }
63}
64
65impl fmt::Display for Dec {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 let normal = self.normal();
68 let sign = if normal.units < 0 { "-" } else { "" };
69 let magnitude = normal.units.unsigned_abs();
70 if normal.scale == 0 {
71 return write!(f, "{sign}{magnitude}");
72 }
73 let step = 10u128.pow(normal.scale);
74 let places = normal.scale as usize;
75 write!(f, "{sign}{}.{:0places$}", magnitude / step, magnitude % step)
76 }
77}
78
79impl FromStr for Dec {
80 type Err = BadDec;
81
82 fn from_str(text: &str) -> Result<Self, Self::Err> {
83 Dec::parse(text)
84 }
85}
86
87impl Serialize for Dec {
88 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
89 serializer.collect_str(self)
90 }
91}
92
93impl<'de> Deserialize<'de> for Dec {
96 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
97 struct Visitor;
98
99 impl de::Visitor<'_> for Visitor {
100 type Value = Dec;
101
102 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str("a decimal string or an integer")
104 }
105
106 fn visit_str<E: de::Error>(self, text: &str) -> Result<Dec, E> {
107 Dec::parse(text).map_err(E::custom)
108 }
109
110 fn visit_u64<E: de::Error>(self, value: u64) -> Result<Dec, E> {
111 Ok(Dec { units: i128::from(value), scale: 0 })
112 }
113
114 fn visit_i64<E: de::Error>(self, value: i64) -> Result<Dec, E> {
115 Ok(Dec { units: i128::from(value), scale: 0 })
116 }
117 }
118
119 deserializer.deserialize_any(Visitor)
120 }
121}
122
123#[cfg(test)]
124#[path = "tests/wire.rs"]
125mod tests;