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