Skip to main content

hawdb_core/
decimal.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Bounded exact decimal values. Arithmetic intermediates have at most 114
16//! digits; stored values never own an arbitrary-precision allocation.
17
18use num_bigint::BigInt;
19use num_traits::{Signed, ToPrimitive, Zero};
20use std::cmp::Ordering;
21use std::fmt::{self, Display, Formatter};
22use std::hash::{Hash, Hasher};
23use std::str::FromStr;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum DecimalError {
27    InvalidLiteral,
28    InvalidType,
29    InvalidEncoding,
30    Overflow,
31    DivisionByZero,
32    /// Exact integer conversion of a value with a nonzero fraction (#1516).
33    Fractional,
34    /// Exact integer conversion of a value outside the BIGINT range.
35    IntegerOutOfRange,
36}
37
38impl Display for DecimalError {
39    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
40        f.write_str(match self {
41            Self::InvalidLiteral => "invalid or overlong decimal literal",
42            Self::InvalidType => "decimal requires precision 1..38 and scale 0..precision",
43            Self::InvalidEncoding => "invalid decimal encoding",
44            Self::Overflow => "decimal result exceeds 38 coefficient digits or scale 38",
45            Self::DivisionByZero => "decimal division by zero",
46            Self::Fractional => {
47                "decimal value has a fractional part; BIGINT requires an exact integer (HawDB does not round)"
48            }
49            Self::IntegerOutOfRange => "decimal value is outside the BIGINT range",
50        })
51    }
52}
53
54impl std::error::Error for DecimalError {}
55
56/// A validated SQL DECIMAL(precision, scale) declaration.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub struct DecimalType {
59    precision: u8,
60    scale: u8,
61}
62
63impl DecimalType {
64    pub const DEFAULT: Self = Self {
65        precision: 38,
66        scale: 0,
67    };
68
69    pub const fn new(precision: u8, scale: u8) -> Result<Self, DecimalError> {
70        if precision == 0 || precision > Decimal::MAX_PRECISION || scale > precision {
71            return Err(DecimalError::InvalidType);
72        }
73        Ok(Self { precision, scale })
74    }
75
76    pub const fn precision(self) -> u8 {
77        self.precision
78    }
79    pub const fn scale(self) -> u8 {
80        self.scale
81    }
82
83    /// Round to the declared scale, then enforce precision on the rounded value.
84    pub fn coerce(self, value: Decimal) -> Result<Decimal, DecimalError> {
85        let value = value.rescale(self.scale)?;
86        if value.precision() > self.precision {
87            return Err(DecimalError::Overflow);
88        }
89        Ok(value)
90    }
91
92    pub const fn accepts(self, value: Decimal) -> bool {
93        value.scale == self.scale && value.precision() <= self.precision
94    }
95}
96
97impl Display for DecimalType {
98    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
99        write!(f, "DECIMAL({},{})", self.precision, self.scale)
100    }
101}
102
103/// An exact signed coefficient times 10 to the negative scale.
104///
105/// Coefficients have at most 38 digits and scales are 0..38. Add, subtract,
106/// multiply and remainder are exact or fail; division and explicit rescaling
107/// round to nearest with midpoint away from zero. Equality, hashing and ordering
108/// are numeric: 1.0 and 1.00 are equal, although display retains their scales.
109#[derive(Clone, Copy)]
110pub struct Decimal {
111    // Byte storage avoids imposing i128 alignment on every Value enum slot.
112    coefficient: [u8; 16],
113    scale: u8,
114}
115
116impl Decimal {
117    pub const MAX_PRECISION: u8 = 38;
118    pub const MAX_COEFFICIENT: i128 = 10_i128.pow(38) - 1;
119    pub const ZERO: Self = Self {
120        coefficient: [0; 16],
121        scale: 0,
122    };
123    pub const ENCODED_LEN: usize = 17;
124    pub const ORDERED_LEN: usize = 40;
125    pub const MAX_LITERAL_BYTES: usize = 256;
126
127    pub const fn new(coefficient: i128, scale: u8) -> Result<Self, DecimalError> {
128        if coefficient.unsigned_abs() > Self::MAX_COEFFICIENT as u128 || scale > 38 {
129            return Err(DecimalError::Overflow);
130        }
131        Ok(Self {
132            coefficient: coefficient.to_le_bytes(),
133            scale,
134        })
135    }
136
137    pub const fn coefficient(self) -> i128 {
138        i128::from_le_bytes(self.coefficient)
139    }
140    pub const fn scale(self) -> u8 {
141        self.scale
142    }
143
144    pub const fn precision(self) -> u8 {
145        let mut value = self.coefficient().unsigned_abs();
146        let mut digits = 1;
147        while value >= 10 {
148            value /= 10;
149            digits += 1;
150        }
151        digits
152    }
153
154    /// The smallest declaration that retains this value's scale.
155    pub const fn decimal_type(self) -> DecimalType {
156        let precision = self.precision();
157        DecimalType {
158            precision: if precision > self.scale {
159                precision
160            } else {
161                self.scale
162            },
163            scale: self.scale,
164        }
165    }
166
167    pub const fn checked_neg(self) -> Self {
168        Self {
169            coefficient: (-self.coefficient()).to_le_bytes(),
170            scale: self.scale,
171        }
172    }
173
174    fn exact(mut coefficient: BigInt, mut scale: u32) -> Result<Self, DecimalError> {
175        let limit = BigInt::from(Self::MAX_COEFFICIENT);
176        while (scale > 38 || coefficient.abs() > limit) && scale > 0 {
177            if !(&coefficient % 10_u8).is_zero() {
178                return Err(DecimalError::Overflow);
179            }
180            coefficient /= 10_u8;
181            scale -= 1;
182        }
183        Self::new(
184            coefficient.to_i128().ok_or(DecimalError::Overflow)?,
185            scale.try_into().map_err(|_| DecimalError::Overflow)?,
186        )
187    }
188
189    fn aligned(self, other: Self) -> (BigInt, BigInt, u8) {
190        let scale = self.scale.max(other.scale);
191        (
192            BigInt::from(self.coefficient()) * ten(u32::from(scale - self.scale)),
193            BigInt::from(other.coefficient()) * ten(u32::from(scale - other.scale)),
194            scale,
195        )
196    }
197
198    pub fn checked_add(self, other: Self) -> Result<Self, DecimalError> {
199        let (left, right, scale) = self.aligned(other);
200        Self::exact(left + right, scale.into())
201    }
202
203    pub fn checked_sub(self, other: Self) -> Result<Self, DecimalError> {
204        self.checked_add(other.checked_neg())
205    }
206
207    pub fn checked_mul(self, other: Self) -> Result<Self, DecimalError> {
208        Self::exact(
209            BigInt::from(self.coefficient()) * BigInt::from(other.coefficient()),
210            u32::from(self.scale) + u32::from(other.scale),
211        )
212    }
213
214    pub fn checked_rem(self, other: Self) -> Result<Self, DecimalError> {
215        if other.coefficient() == 0 {
216            return Err(DecimalError::DivisionByZero);
217        }
218        let (left, right, scale) = self.aligned(other);
219        Self::exact(left % right, scale.into())
220    }
221
222    /// Round once to at most 38 coefficient digits and scale at most 38.
223    /// Very small quotients may round to zero at scale 38.
224    pub fn checked_div(self, other: Self) -> Result<Self, DecimalError> {
225        if other.coefficient() == 0 {
226            return Err(DecimalError::DivisionByZero);
227        }
228        let numerator = BigInt::from(self.coefficient()) * ten(other.scale.into());
229        let denominator = BigInt::from(other.coefficient()) * ten(self.scale.into());
230        let integral = (&numerator / &denominator).abs();
231        let digits = if integral.is_zero() {
232            0
233        } else {
234            integral.to_string().len()
235        };
236        if digits > 38 {
237            return Err(DecimalError::Overflow);
238        }
239        let mut scale = 38 - digits as u32;
240        loop {
241            let scaled = &numerator * ten(scale);
242            let mut quotient = &scaled / &denominator;
243            let remainder = &scaled % &denominator;
244            if remainder.abs() * 2_u8 >= denominator.abs() {
245                quotient += if scaled.sign() == denominator.sign() {
246                    1_i8
247                } else {
248                    -1
249                };
250            }
251            if quotient.abs() <= BigInt::from(Self::MAX_COEFFICIENT) {
252                return Self::new(
253                    quotient.to_i128().ok_or(DecimalError::Overflow)?,
254                    scale as u8,
255                );
256            }
257            if scale == 0 {
258                return Err(DecimalError::Overflow);
259            }
260            // Recompute from the original rational to avoid double rounding.
261            scale -= 1;
262        }
263    }
264
265    pub fn rescale(self, scale: u8) -> Result<Self, DecimalError> {
266        if scale > 38 {
267            return Err(DecimalError::Overflow);
268        }
269        if scale >= self.scale {
270            return Self::new(
271                (BigInt::from(self.coefficient()) * ten(u32::from(scale - self.scale)))
272                    .to_i128()
273                    .ok_or(DecimalError::Overflow)?,
274                scale,
275            );
276        }
277        let divisor = 10_i128.pow(u32::from(self.scale - scale));
278        let mut quotient = self.coefficient() / divisor;
279        // Multiplying the remainder by two could overflow i128.
280        if (self.coefficient() % divisor).unsigned_abs() >= (divisor / 2) as u128 {
281            quotient += self.coefficient().signum();
282        }
283        Self::new(quotient, scale)
284    }
285
286    /// Exact integral conversion, rejecting fractions and BIGINT overflow.
287    pub fn to_i64(self) -> Result<i64, DecimalError> {
288        let divisor = 10_i128.pow(self.scale.into());
289        let coefficient = self.coefficient();
290        if coefficient % divisor != 0 {
291            return Err(DecimalError::Fractional);
292        }
293        (coefficient / divisor)
294            .try_into()
295            .map_err(|_| DecimalError::IntegerOutOfRange)
296    }
297
298    pub fn to_le_bytes(self) -> [u8; Self::ENCODED_LEN] {
299        let mut bytes = [0; Self::ENCODED_LEN];
300        bytes[..16].copy_from_slice(&self.coefficient);
301        bytes[16] = self.scale;
302        bytes
303    }
304
305    pub fn from_le_bytes(bytes: [u8; Self::ENCODED_LEN]) -> Result<Self, DecimalError> {
306        Self::new(
307            i128::from_le_bytes(bytes[..16].try_into().expect("fixed coefficient width")),
308            bytes[16],
309        )
310        .map_err(|_| DecimalError::InvalidEncoding)
311    }
312
313    /// Canonical, fixed-width numeric order. Existing scalar tags are external.
314    pub fn to_ordered_bytes(self) -> [u8; Self::ORDERED_LEN] {
315        let mut encoded = [0; Self::ORDERED_LEN];
316        let coefficient = self.coefficient();
317        if coefficient == 0 {
318            encoded[0] = 1;
319            return encoded;
320        }
321        let mut value = coefficient.unsigned_abs();
322        let mut digits = [0; 38];
323        let mut first = 38;
324        while value != 0 {
325            first -= 1;
326            digits[first] = (value % 10) as u8;
327            value /= 10;
328        }
329        let count = 38 - first;
330        encoded[0] = if coefficient < 0 { 0 } else { 2 };
331        encoded[1] = (count + 38 - usize::from(self.scale)) as u8;
332        encoded[2..2 + count].copy_from_slice(&digits[first..]);
333        if coefficient < 0 {
334            encoded[1..].iter_mut().for_each(|byte| *byte = !*byte);
335        }
336        encoded
337    }
338
339    pub fn from_ordered_bytes(mut encoded: [u8; Self::ORDERED_LEN]) -> Result<Self, DecimalError> {
340        match encoded[0] {
341            0 => encoded[1..].iter_mut().for_each(|byte| *byte = !*byte),
342            1 if encoded[1..].iter().all(|byte| *byte == 0) => return Ok(Self::ZERO),
343            2 => (),
344            _ => return Err(DecimalError::InvalidEncoding),
345        }
346        if !(1..=76).contains(&encoded[1])
347            || encoded[2] == 0
348            || encoded[2..].iter().any(|byte| *byte > 9)
349        {
350            return Err(DecimalError::InvalidEncoding);
351        }
352        let mut coefficient = 0_i128;
353        for digit in &encoded[2..] {
354            coefficient = coefficient * 10 + i128::from(*digit);
355        }
356        if encoded[0] == 0 {
357            coefficient = -coefficient;
358        }
359        let mut scale = 76 - encoded[1];
360        while scale > 38 && coefficient % 10 == 0 {
361            coefficient /= 10;
362            scale -= 1;
363        }
364        Self::new(coefficient, scale).map_err(|_| DecimalError::InvalidEncoding)
365    }
366
367    /// Next value in the entire bounded Decimal domain, for exclusive prefix
368    /// bounds. Adding one unit of the input scale would skip representable keys.
369    pub fn next_up(self) -> Option<Self> {
370        let mut scaled = BigInt::from(self.coefficient()) * ten(u32::from(38 - self.scale));
371        for scale in (0..=38).rev() {
372            let candidate = &scaled + 1_u8;
373            if candidate.abs() <= BigInt::from(Self::MAX_COEFFICIENT) {
374                return Self::new(candidate.to_i128()?, scale).ok();
375            }
376            let negative_fraction = scaled.is_negative() && !(&scaled % 10_u8).is_zero();
377            scaled /= 10_u8;
378            if negative_fraction {
379                scaled -= 1_u8;
380            }
381        }
382        None
383    }
384
385    fn normalized(self) -> (i128, u8) {
386        let mut coefficient = self.coefficient();
387        let mut scale = self.scale;
388        while scale > 0 && coefficient % 10 == 0 {
389            coefficient /= 10;
390            scale -= 1;
391        }
392        (coefficient, scale)
393    }
394}
395
396fn ten(power: u32) -> BigInt {
397    BigInt::from(10_u8).pow(power)
398}
399
400impl From<i64> for Decimal {
401    fn from(value: i64) -> Self {
402        Self {
403            coefficient: i128::from(value).to_le_bytes(),
404            scale: 0,
405        }
406    }
407}
408
409impl PartialEq for Decimal {
410    fn eq(&self, other: &Self) -> bool {
411        self.normalized() == other.normalized()
412    }
413}
414impl Eq for Decimal {}
415impl PartialOrd for Decimal {
416    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
417        Some(self.cmp(other))
418    }
419}
420impl Ord for Decimal {
421    fn cmp(&self, other: &Self) -> Ordering {
422        self.to_ordered_bytes().cmp(&other.to_ordered_bytes())
423    }
424}
425impl Hash for Decimal {
426    fn hash<H: Hasher>(&self, state: &mut H) {
427        self.normalized().hash(state);
428    }
429}
430impl fmt::Debug for Decimal {
431    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
432        write!(f, "Decimal({self})")
433    }
434}
435impl Display for Decimal {
436    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
437        let coefficient = self.coefficient();
438        if coefficient < 0 {
439            f.write_str("-")?;
440        }
441        let magnitude = coefficient.unsigned_abs();
442        if self.scale == 0 {
443            return write!(f, "{magnitude}");
444        }
445        let divisor = 10_u128.pow(self.scale.into());
446        write!(
447            f,
448            "{}.{:0width$}",
449            magnitude / divisor,
450            magnitude % divisor,
451            width = usize::from(self.scale)
452        )
453    }
454}
455
456impl FromStr for Decimal {
457    type Err = DecimalError;
458
459    fn from_str(text: &str) -> Result<Self, Self::Err> {
460        if text.is_empty() || text.len() > Self::MAX_LITERAL_BYTES {
461            return Err(DecimalError::InvalidLiteral);
462        }
463        let (negative, unsigned) = match text.as_bytes()[0] {
464            b'-' => (true, &text[1..]),
465            b'+' => (false, &text[1..]),
466            _ => (false, text),
467        };
468        let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
469            Some(at) => {
470                let exponent = unsigned[at + 1..]
471                    .parse::<i16>()
472                    .map_err(|_| DecimalError::InvalidLiteral)?;
473                if exponent.unsigned_abs() > 1024 {
474                    return Err(DecimalError::Overflow);
475                }
476                (&unsigned[..at], exponent)
477            }
478            None => (unsigned, 0),
479        };
480        let mut digits = [0_u8; Self::MAX_LITERAL_BYTES];
481        let mut count = 0;
482        let mut fraction = 0_i16;
483        let mut point = false;
484        for byte in mantissa.bytes() {
485            match byte {
486                b'.' if !point => point = true,
487                b'0'..=b'9' => {
488                    digits[count] = byte - b'0';
489                    count += 1;
490                    fraction += i16::from(point);
491                }
492                _ => return Err(DecimalError::InvalidLiteral),
493            }
494        }
495        if count == 0 {
496            return Err(DecimalError::InvalidLiteral);
497        }
498        let mut scale = fraction - exponent;
499        let Some(first) = digits[..count].iter().position(|digit| *digit != 0) else {
500            return Self::new(0, scale.clamp(0, 38) as u8);
501        };
502        while scale > 0 && (count - first > 38 || scale > 38) && digits[count - 1] == 0 {
503            count -= 1;
504            scale -= 1;
505        }
506        if count - first > 38
507            || scale > 38
508            || i32::try_from(count - first).expect("bounded literal") - i32::from(scale.min(0)) > 38
509        {
510            return Err(DecimalError::Overflow);
511        }
512        let mut coefficient = 0_i128;
513        for digit in &digits[first..count] {
514            coefficient = coefficient * 10 + i128::from(*digit);
515        }
516        if scale < 0 {
517            coefficient *= 10_i128.pow(u32::from(scale.unsigned_abs()));
518            scale = 0;
519        }
520        Self::new(
521            if negative { -coefficient } else { coefficient },
522            scale as u8,
523        )
524    }
525}
526
527#[cfg(test)]
528mod tests;