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    /// Canonical signed coefficient.
49    #[must_use]
50    pub const fn mantissa(self) -> i128 {
51        self.mantissa
52    }
53    /// Canonical fractional scale.
54    #[must_use]
55    pub const fn scale(self) -> u32 {
56        self.scale
57    }
58}
59impl Ord for Decimal {
60    fn cmp(&self, other: &Self) -> Ordering {
61        // Adapt IcyDB's bounded exact alignment. If multiplication overflows,
62        // its sign determines the order beyond the other i128 coefficient.
63        match self.scale.cmp(&other.scale) {
64            Ordering::Equal => self.mantissa.cmp(&other.mantissa),
65            Ordering::Less => self
66                .mantissa
67                .checked_mul(10_i128.pow(other.scale - self.scale))
68                .map_or_else(|| self.mantissa.cmp(&0), |v| v.cmp(&other.mantissa)),
69            Ordering::Greater => other
70                .mantissa
71                .checked_mul(10_i128.pow(self.scale - other.scale))
72                .map_or_else(|| 0.cmp(&other.mantissa), |v| self.mantissa.cmp(&v)),
73        }
74    }
75}
76impl PartialOrd for Decimal {
77    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
78        Some(self.cmp(other))
79    }
80}
81/// Invalid syntax or a value outside Decimal's exact coefficient/scale domain.
82#[derive(Clone, Copy, Debug, Eq, PartialEq)]
83pub struct ParseDecimalError;
84impl fmt::Display for ParseDecimalError {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.write_str("invalid or out-of-range decimal")
87    }
88}
89impl std::error::Error for ParseDecimalError {}
90
91impl FromStr for Decimal {
92    type Err = ParseDecimalError;
93    fn from_str(input: &str) -> Result<Self, Self::Err> {
94        let input = input.trim();
95        let (negative, unsigned) = if let Some(rest) = input.strip_prefix('-') {
96            (true, rest)
97        } else {
98            (false, input.strip_prefix('+').unwrap_or(input))
99        };
100        let mut parts = unsigned.split('.');
101        let integer = parts.next().ok_or(ParseDecimalError)?;
102        let fractional = parts.next().unwrap_or("");
103        if parts.next().is_some()
104            || (integer.is_empty() && fractional.is_empty())
105            || !integer
106                .bytes()
107                .chain(fractional.bytes())
108                .all(|b| b.is_ascii_digit())
109        {
110            return Err(ParseDecimalError);
111        }
112        let scale = u32::try_from(fractional.len()).map_err(|_| ParseDecimalError)?;
113        // Subtract negative digits directly, retaining the full i128::MIN domain.
114        let mantissa = integer
115            .bytes()
116            .chain(fractional.bytes())
117            .try_fold(0_i128, |value, digit| {
118                let value = value.checked_mul(10)?;
119                let digit = i128::from(digit - b'0');
120                if negative {
121                    value.checked_sub(digit)
122                } else {
123                    value.checked_add(digit)
124                }
125            })
126            .ok_or(ParseDecimalError)?;
127        Self::try_new(mantissa, scale).ok_or(ParseDecimalError)
128    }
129}
130impl fmt::Display for Decimal {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        if self.mantissa < 0 {
133            f.write_str("-")?;
134        }
135        let mut digits = self.mantissa.unsigned_abs().to_string();
136        let scale = self.scale as usize;
137        if scale == 0 {
138            return f.write_str(&digits);
139        }
140        if digits.len() <= scale {
141            f.write_str("0.")?;
142            for _ in digits.len()..scale {
143                f.write_str("0")?;
144            }
145            f.write_str(&digits)
146        } else {
147            let fractional = digits.split_off(digits.len() - scale);
148            write!(f, "{digits}.{fractional}")
149        }
150    }
151}
152
153impl Decimal {
154    /// Return the exact coefficient at a declared scale, or refuse excess
155    /// precision, coefficient overflow or a scale above 28. Never rounds.
156    #[must_use]
157    pub fn coefficient_at_scale(self, scale: u32) -> Option<i128> {
158        if scale > Self::MAX_SCALE || scale < self.scale {
159            return None;
160        }
161        self.mantissa.checked_mul(10_i128.pow(scale - self.scale))
162    }
163
164    // IcyDB's bounded sign/exponent/digits representation. Equivalent values
165    // share bytes without attaching a schema or a conversion layer to operands.
166    pub(crate) fn append_ordered(self, out: &mut Vec<u8>) {
167        if self.mantissa == 0 {
168            out.push(1);
169            return;
170        }
171        let mut digits = [0_u8; 39];
172        let mut position = digits.len();
173        let mut magnitude = self.mantissa.unsigned_abs();
174        while magnitude != 0 {
175            position -= 1;
176            digits[position] = b'0' + (magnitude % 10) as u8;
177            magnitude /= 10;
178        }
179        let exponent = (digits.len() - position - 1) as i32 - self.scale as i32;
180        let mut exponent = exponent.to_be_bytes();
181        exponent[0] ^= 0x80;
182        let negative = self.mantissa < 0;
183        out.push(if negative { 0 } else { 2 });
184        out.extend(
185            exponent
186                .into_iter()
187                .chain(digits[position..].iter().copied())
188                .map(|b| if negative { !b } else { b }),
189        );
190        out.push(if negative { 255 } else { 0 });
191    }
192
193    pub(crate) fn read_ordered(bytes: &[u8]) -> Option<(Self, usize)> {
194        let sign = *bytes.first()?;
195        if sign == 1 {
196            return Some((Self::ZERO, 1));
197        }
198        if sign != 0 && sign != 2 {
199            return None;
200        }
201        let negative = sign == 0;
202        let undo = |b: u8| if negative { !b } else { b };
203        let mut exponent: [u8; 4] = bytes.get(1..5)?.try_into().ok()?;
204        exponent = exponent.map(undo);
205        exponent[0] ^= 0x80;
206        let exponent = i32::from_be_bytes(exponent);
207        let mut mantissa = 0_i128;
208        for (n, byte) in bytes.get(5..)?.iter().take(40).enumerate() {
209            let digit = undo(*byte);
210            if digit == 0 {
211                if n == 0 || mantissa == 0 {
212                    return None;
213                }
214                let scale = (n as i64 - 1).checked_sub(i64::from(exponent))?;
215                let scale = u32::try_from(scale).ok()?;
216                let value = Self::try_new(mantissa, scale)?;
217                // No redundant fractional zeros, excess scale or alternate zero.
218                if value.scale != scale {
219                    return None;
220                }
221                return Some((value, 6 + n));
222            }
223            if !digit.is_ascii_digit() || (n == 0 && digit == b'0') || n == 39 {
224                return None;
225            }
226            mantissa = mantissa.checked_mul(10)?;
227            let digit = i128::from(digit - b'0');
228            mantissa = if negative {
229                mantissa.checked_sub(digit)?
230            } else {
231                mantissa.checked_add(digit)?
232            };
233        }
234        None
235    }
236}