Skip to main content

ic_db/
decimal.rs

1//! Canonical decimal values adapted from frozen IcyDB 6d421e3.
2//! Exact comparison and text parsing; aggregate arithmetic is a separate contract.
3
4use std::{cmp::Ordering, fmt, str::FromStr};
5
6/// Exact base-ten value with a signed 128-bit mantissa and scale 0–28.
7/// Construction removes fractional trailing zeros; all zero values share one
8/// representation. No floating-point conversion or implicit rounding is used.
9#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
10pub struct Decimal {
11    mantissa: i128,
12    scale: u32,
13}
14impl Decimal {
15    /// Canonical zero.
16    pub const ZERO: Self = Self {
17        mantissa: 0,
18        scale: 0,
19    };
20    /// Smallest scale-zero value.
21    pub const MIN: Self = Self {
22        mantissa: i128::MIN,
23        scale: 0,
24    };
25    /// Largest scale-zero value.
26    pub const MAX: Self = Self {
27        mantissa: i128::MAX,
28        scale: 0,
29    };
30    /// Maximum fractional scale after exact normalization.
31    pub const MAX_SCALE: u32 = 28;
32    /// Construct exactly, removing fractional trailing zeros. Excess scale is
33    /// accepted only if normalization brings it into range without rounding.
34    #[must_use]
35    pub const fn try_new(mut mantissa: i128, mut scale: u32) -> Option<Self> {
36        if mantissa == 0 {
37            return Some(Self::ZERO);
38        }
39        while scale > 0 && mantissa % 10 == 0 {
40            mantissa /= 10;
41            scale -= 1;
42        }
43
44        if scale > Self::MAX_SCALE {
45            None
46        } else {
47            Some(Self { mantissa, scale })
48        }
49    }
50
51    /// Canonical signed coefficient.
52    #[must_use]
53    pub const fn mantissa(self) -> i128 {
54        self.mantissa
55    }
56
57    /// Canonical fractional scale.
58    #[must_use]
59    pub const fn scale(self) -> u32 {
60        self.scale
61    }
62}
63// Exact decimal text also round-trips the full i128 domain through JSON.
64impl serde::Serialize for Decimal {
65    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
66        serializer.collect_str(self)
67    }
68}
69
70impl<'de> serde::Deserialize<'de> for Decimal {
71    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
72        String::deserialize(deserializer)?
73            .parse()
74            .map_err(serde::de::Error::custom)
75    }
76}
77
78impl Ord for Decimal {
79    fn cmp(&self, other: &Self) -> Ordering {
80        // Adapt IcyDB's bounded exact alignment. If multiplication overflows,
81        // its sign determines the order beyond the other i128 coefficient.
82        match self.scale.cmp(&other.scale) {
83            Ordering::Equal => self.mantissa.cmp(&other.mantissa),
84            Ordering::Less => self
85                .mantissa
86                .checked_mul(10_i128.pow(other.scale - self.scale))
87                .map_or_else(|| self.mantissa.cmp(&0), |v| v.cmp(&other.mantissa)),
88            Ordering::Greater => other
89                .mantissa
90                .checked_mul(10_i128.pow(self.scale - other.scale))
91                .map_or_else(|| 0.cmp(&other.mantissa), |v| self.mantissa.cmp(&v)),
92        }
93    }
94}
95impl PartialOrd for Decimal {
96    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
97        Some(self.cmp(other))
98    }
99}
100/// Invalid syntax or a value outside Decimal's exact coefficient/scale domain.
101#[derive(Clone, Copy, Debug, Eq, PartialEq)]
102pub struct ParseDecimalError;
103impl fmt::Display for ParseDecimalError {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        f.write_str("invalid or out-of-range decimal")
106    }
107}
108impl std::error::Error for ParseDecimalError {}
109
110impl FromStr for Decimal {
111    type Err = ParseDecimalError;
112    fn from_str(input: &str) -> Result<Self, Self::Err> {
113        let input = input.trim();
114        let (negative, unsigned) = if let Some(rest) = input.strip_prefix('-') {
115            (true, rest)
116        } else {
117            (false, input.strip_prefix('+').unwrap_or(input))
118        };
119        let mut parts = unsigned.split('.');
120        let integer = parts.next().ok_or(ParseDecimalError)?;
121        let fractional = parts.next().unwrap_or("");
122        if parts.next().is_some()
123            || (integer.is_empty() && fractional.is_empty())
124            || !integer
125                .bytes()
126                .chain(fractional.bytes())
127                .all(|b| b.is_ascii_digit())
128        {
129            return Err(ParseDecimalError);
130        }
131        let scale = u32::try_from(fractional.len()).map_err(|_| ParseDecimalError)?;
132        // Subtract negative digits directly, retaining the full i128::MIN domain.
133        let mantissa = integer
134            .bytes()
135            .chain(fractional.bytes())
136            .try_fold(0_i128, |value, digit| {
137                let value = value.checked_mul(10)?;
138                let digit = i128::from(digit - b'0');
139
140                if negative {
141                    value.checked_sub(digit)
142                } else {
143                    value.checked_add(digit)
144                }
145            })
146            .ok_or(ParseDecimalError)?;
147
148        Self::try_new(mantissa, scale).ok_or(ParseDecimalError)
149    }
150}
151impl fmt::Display for Decimal {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        if self.mantissa < 0 {
154            f.write_str("-")?;
155        }
156        let mut digits = self.mantissa.unsigned_abs().to_string();
157        let scale = self.scale as usize;
158        if scale == 0 {
159            return f.write_str(&digits);
160        }
161
162        if digits.len() <= scale {
163            f.write_str("0.")?;
164            for _ in digits.len()..scale {
165                f.write_str("0")?;
166            }
167
168            f.write_str(&digits)
169        } else {
170            let fractional = digits.split_off(digits.len() - scale);
171
172            write!(f, "{digits}.{fractional}")
173        }
174    }
175}
176
177impl Decimal {
178    /// Return the exact coefficient at a declared scale, or refuse excess
179    /// precision, coefficient overflow or a scale above 28. Never rounds.
180    #[must_use]
181    pub fn coefficient_at_scale(self, scale: u32) -> Option<i128> {
182        if scale > Self::MAX_SCALE || scale < self.scale {
183            return None;
184        }
185
186        self.mantissa.checked_mul(10_i128.pow(scale - self.scale))
187    }
188
189    // IcyDB's bounded sign/exponent/digits representation. Equivalent values
190    // share bytes without attaching a schema or a conversion layer to operands.
191    pub(crate) fn append_ordered(self, out: &mut Vec<u8>) {
192        if self.mantissa == 0 {
193            out.push(1);
194
195            return;
196        }
197        let mut digits = [0_u8; 39];
198        let mut position = digits.len();
199        let mut magnitude = self.mantissa.unsigned_abs();
200        while magnitude != 0 {
201            position -= 1;
202            digits[position] = b'0' + (magnitude % 10) as u8;
203            magnitude /= 10;
204        }
205        let exponent = (digits.len() - position - 1) as i32 - self.scale as i32;
206        let mut exponent = exponent.to_be_bytes();
207        exponent[0] ^= 0x80;
208        let negative = self.mantissa < 0;
209        out.push(if negative { 0 } else { 2 });
210        out.extend(
211            exponent
212                .into_iter()
213                .chain(digits[position..].iter().copied())
214                .map(|b| if negative { !b } else { b }),
215        );
216        out.push(if negative { 255 } else { 0 });
217    }
218
219    pub(crate) fn read_ordered(bytes: &[u8]) -> Option<(Self, usize)> {
220        let sign = *bytes.first()?;
221        if sign == 1 {
222            return Some((Self::ZERO, 1));
223        }
224        if sign != 0 && sign != 2 {
225            return None;
226        }
227        let negative = sign == 0;
228        let undo = |b: u8| if negative { !b } else { b };
229        let mut exponent: [u8; 4] = bytes.get(1..5)?.try_into().ok()?;
230        exponent = exponent.map(undo);
231        exponent[0] ^= 0x80;
232        let exponent = i32::from_be_bytes(exponent);
233        let mut mantissa = 0_i128;
234        for (n, byte) in bytes.get(5..)?.iter().take(40).enumerate() {
235            let digit = undo(*byte);
236            if digit == 0 {
237                if n == 0 || mantissa == 0 {
238                    return None;
239                }
240                let scale = (n as i64 - 1).checked_sub(i64::from(exponent))?;
241                let scale = u32::try_from(scale).ok()?;
242                let value = Self::try_new(mantissa, scale)?;
243                // No redundant fractional zeros, excess scale or alternate zero.
244                if value.scale != scale {
245                    return None;
246                }
247
248                return Some((value, 6 + n));
249            }
250            if !digit.is_ascii_digit() || (n == 0 && digit == b'0') || n == 39 {
251                return None;
252            }
253            mantissa = mantissa.checked_mul(10)?;
254            let digit = i128::from(digit - b'0');
255            mantissa = if negative {
256                mantissa.checked_sub(digit)?
257            } else {
258                mantissa.checked_add(digit)?
259            };
260        }
261
262        None
263    }
264}