Skip to main content

df_hyperliquid_core/utils/dec/
wire.rs

1//! A decimal as the venue writes it: read with an optional sign and at most one point, written back
2//! with no trailing zeros and no exponent, and the same through serde.
3
4use std::{fmt, str::FromStr};
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
7
8use crate::utils::dec::{Dec, MAX_SCALE};
9
10/// Why text did not read as a [`Dec`]. Each variant holds the text given.
11#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
12#[non_exhaustive]
13pub enum BadDec {
14    /// Empty, an exponent, a second point, or any character other than a
15    /// leading sign, digits and one point.
16    #[error("`{0}` is not a decimal number")]
17    NotANumber(String),
18    /// More than eighteen places behind the point once trailing zeros are dropped.
19    #[error("`{0}` has more than eighteen decimal places")]
20    TooFine(String),
21    /// The digits do not fit in an `i128`.
22    #[error("`{0}` is larger than this build can count")]
23    OutOfRange(String),
24}
25
26impl Dec {
27    /// Reads what the venue writes: an optional sign, digits, and at most one
28    /// point. No exponent, since the venue never sends one.
29    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    /// The canonical spelling: no trailing zeros, no exponent, `0` for zero.
59    /// This is the string that is hashed, so it must match the venue's clients.
60    #[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
94/// From the venue's decimal strings, or a JSON integer. A JSON fraction is
95/// refused: it has already been through a float.
96impl<'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;