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