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