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        match Dec::parse_short(text.as_bytes()) {
31            Some(dec) => Ok(dec),
32            None => Dec::parse_long(text),
33        }
34    }
35
36    /// What the venue sends almost always: an optional `-`, then at most nineteen digits and one
37    /// point, which fit in a `u64`. Anything else (a `+`, spaces, more digits, a stray character)
38    /// is `None` and goes to [`Dec::parse_long`], which reads it or says why not. Both give the
39    /// same `units` and `scale` for every text this one reads.
40    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        // At most eighteen places: nineteen bytes hold at most eighteen digits after a point.
62        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    /// Every spelling [`Dec::parse`] takes, and the reason for one it does not.
75    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    /// The canonical spelling: no trailing zeros, no exponent, `0` for zero.
105    /// This is the string that is hashed, so it must match the venue's clients.
106    #[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
140/// From the venue's decimal strings, or a JSON integer. A JSON fraction is
141/// refused: it has already been through a float.
142impl<'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;