feldera_fxp/
lib.rs

1// Warn about missing docs, but not for item declared with `#[cfg(test)]`.
2#![cfg_attr(not(test), warn(missing_docs))]
3
4//! Decimal arithmetic.
5//!
6//! This crate primarily provides the [Fixed] type for decimal arithmetic with
7//! precision and scale supplied as type parameters.  It also provides
8//! [DynamicDecimal], which has 38 digits of precision and a dynamic scale.  The
9//! latter is mainly provided for serialization and does not include much in the
10//! way of arithmetic.
11//!
12//! # Features
13//!
14//! The following `cargo` features are provided:
15//!
16//! * `serde`: Implements [serde] traits for serializing and deserializing
17//!   [Fixed] and [DynamicDecimal].
18//!
19//! * `rkyv`: Implements [rkyv] traits for serializing and deserializing [Fixed]
20//!   and [DynamicDecimal].
21//!
22//! * `validation` (depends on `rkyv`): Implements [rkyv] traits for validation.
23//!
24//! * `size_of`: Implements [size_of] traits for measuring data sizes.
25//!
26//! * `dbsp` (depends on `serde`, `rkyv`, and `size_of`): Implements [DBSP]
27//!   traits for [Fixed] and [DynamicDecimal].
28//!
29//! [rkyv]: https://rkyv.org/
30//! [serde]: https://serde.rs/
31//! [size_of]: https://docs.rs/size-of/latest/size_of/
32//! [DBSP]: https://docs.rs/dbsp/latest/dbsp/
33
34use std::{cmp::Ordering, io::Write, num::IntErrorKind};
35
36use smallvec::{Array, SmallVec};
37
38#[cfg(feature = "dbsp")]
39mod dbsp_impl;
40
41#[cfg(feature = "serde")]
42mod serde_impl;
43mod u256;
44
45#[cfg(feature = "rkyv")]
46mod rkyv_impl;
47
48mod dynamic;
49pub use dynamic::DynamicDecimal;
50
51mod fixed;
52pub use fixed::Fixed;
53
54/// A maximum-precision `Fixed` with no decimal places.
55pub type FixedInteger = Fixed<38, 0>;
56
57fn debug_decimal(value: i128, s: usize, f: &mut std::fmt::Formatter) -> std::fmt::Result {
58    let mut buf = SmallVec::<[u8; 64]>::new();
59    write!(&mut buf, "{:01$}", value.unsigned_abs(), s + 1).unwrap();
60    let d = buf.len() - s;
61    while buf.len() > d && buf.ends_with(b"0") {
62        buf.pop();
63    }
64    // SAFETY: `buf` contains only ASCII characters.
65    let s = unsafe { str::from_utf8_unchecked(&buf) };
66    let (integer, fraction) = s.split_at(d);
67    let sign = if value < 0 { "-" } else { "" };
68    write!(f, "{sign}{integer}")?;
69    if !fraction.is_empty() {
70        write!(f, ".{fraction}")?;
71    }
72    Ok(())
73}
74
75fn display_decimal(value: i128, s: usize, f: &mut std::fmt::Formatter) -> std::fmt::Result {
76    let mut buf = SmallVec::<[u8; 64]>::new();
77    write!(&mut buf, "{:01$}", value.abs(), s + 1).unwrap();
78    debug_assert!(buf.len() > s);
79    let decimals = if let Some(precision) = f.precision() {
80        match precision.cmp(&s) {
81            Ordering::Less => {
82                let new_len = buf.len() - (s - precision);
83                let mut discard = buf[new_len..].iter();
84                enum Rounding {
85                    Up,
86                    Down,
87                    Even,
88                }
89                impl Rounding {
90                    fn round<A>(&self, s: &mut SmallVec<A>)
91                    where
92                        A: Array<Item = u8>,
93                    {
94                        let round_up = match self {
95                            Rounding::Down => false,
96                            Rounding::Up => true,
97                            Rounding::Even => s.last().unwrap() % 2 == 1,
98                        };
99                        if round_up {
100                            let mut nines = 0;
101                            let c = loop {
102                                match s.pop() {
103                                    Some(b'9') => nines += 1,
104                                    Some(c) => break c,
105                                    None => break b'0',
106                                }
107                            };
108                            s.push(c + 1);
109                            for _ in 0..nines {
110                                s.push(b'0');
111                            }
112                        }
113                    }
114                }
115                let rounding = match discard.next().unwrap() {
116                    b'0'..=b'4' => Rounding::Down,
117                    b'5' => loop {
118                        match discard.next() {
119                            Some(b'0') => (),
120                            Some(_) => break Rounding::Up,
121                            None => break Rounding::Even,
122                        }
123                    },
124                    b'6'..=b'9' => Rounding::Up,
125                    _ => unreachable!(),
126                };
127                buf.truncate(new_len);
128                rounding.round(&mut buf);
129            }
130            Ordering::Equal => (),
131            Ordering::Greater => {
132                for _ in s..precision {
133                    buf.push(b'0');
134                }
135            }
136        }
137        precision
138    } else {
139        let mut decimals = s;
140        while decimals > 0 && buf.ends_with(b"0") {
141            buf.pop();
142            decimals -= 1;
143        }
144        decimals
145    };
146    if decimals > 0 {
147        buf.insert(buf.len() - decimals, b'.');
148    }
149
150    // SAFETY: `buf` contains only ASCII characters.
151    f.pad_integral(value >= 0, "", unsafe { str::from_utf8_unchecked(&buf) })
152}
153
154/// Parses decimal string `s` into `(sig,exp)`, representing `sig * 10**exp`.
155///
156/// Adds `scale` to the returned exponent, which is just a convenience.
157fn parse_decimal(s: &str, scale: i32) -> Result<(i128, i32), ParseDecimalError> {
158    // Accumulate digits into `value`.  Adjust `exponent` such that the
159    // parsed value is `value / 10**exponent`.
160    let mut value = 0;
161    let mut exponent = scale;
162
163    let mut saw_dot = false;
164    let mut saw_digit = false;
165
166    let mut sign = None;
167    enum Sign {
168        Positive,
169        Negative,
170    }
171
172    let mut iter = s.chars();
173    while let Some(c) = iter.next() {
174        match c {
175            '-' | '+' if sign.is_some() => return Err(ParseDecimalError::SyntaxError),
176            '-' => {
177                sign = Some(Sign::Negative);
178            }
179            '+' => {
180                sign = Some(Sign::Positive);
181            }
182            '0'..='9' => {
183                saw_digit = true;
184                if value < i128::MAX / 10 {
185                    value = value * 10 + (c as u8 - b'0') as i128;
186                    if saw_dot {
187                        exponent -= 1;
188                    }
189                } else if !saw_dot {
190                    exponent = exponent
191                        .checked_add(1)
192                        .ok_or(ParseDecimalError::OutOfRange)?;
193                }
194            }
195            '.' => {
196                if saw_dot {
197                    return Err(ParseDecimalError::SyntaxError);
198                }
199                saw_dot = true;
200            }
201            'e' | 'E' => {
202                if !saw_digit {
203                    return Err(ParseDecimalError::SyntaxError);
204                }
205                let e: i32 = match iter.as_str().parse() {
206                    Ok(e) => e,
207                    Err(error) => {
208                        return match error.kind() {
209                            IntErrorKind::Zero => unreachable!(),
210                            IntErrorKind::PosOverflow => {
211                                if value != 0 {
212                                    Err(ParseDecimalError::OutOfRange)
213                                } else {
214                                    Ok((0, 0))
215                                }
216                            }
217                            IntErrorKind::NegOverflow => Ok((0, 0)),
218                            _ => Err(ParseDecimalError::SyntaxError),
219                        }
220                    }
221                };
222                exponent = match exponent.checked_add(e) {
223                    Some(exponent) => exponent,
224                    None => {
225                        if e > 0 {
226                            // Don't see any way that `value` can be
227                            // zero, since we only have a positive
228                            // `exponent` if `value` would otherwise
229                            // overflow.
230                            debug_assert_ne!(value, 0);
231                            return Err(ParseDecimalError::OutOfRange);
232                        } else {
233                            return Ok((0, 0));
234                        }
235                    }
236                };
237                break;
238            }
239            _ => return Err(ParseDecimalError::SyntaxError),
240        }
241    }
242    if !saw_digit {
243        return Err(ParseDecimalError::SyntaxError);
244    }
245    let value = match sign {
246        Some(Sign::Negative) => -value,
247        _ => value,
248    };
249    Ok((value, exponent))
250}
251
252/// Error that can be returned when parsing [Fixed] or [DynamicDecimal].
253#[derive(Copy, Clone, Debug, PartialEq, Eq)]
254pub enum ParseDecimalError {
255    /// Invalid syntax.
256    SyntaxError,
257
258    /// Out of valid range.
259    ///
260    /// Underflow is rounded to zero, so this error is only returned when the
261    /// absolute value exceeds the type's range.
262    OutOfRange,
263}
264
265/// Error returned for operations that would produce an out-of-range result.
266#[derive(Copy, Clone, Debug, PartialEq, Eq)]
267pub struct OutOfRange;
268
269/// Returns `10**exponent`, or `None` if `exponent > 38` (because the result
270/// would be greater than `i128::MAX`).
271const fn checked_pow10(exponent: u32) -> Option<i128> {
272    10i128.checked_pow(exponent)
273}
274
275/// Returns `10**exponent`.
276///
277/// # Panic
278///
279/// Panics if `exponent > 38` (because the result would be greater than
280/// `i128::MAX`).
281const fn pow10(exponent: usize) -> i128 {
282    10i128.checked_pow(exponent as u32).unwrap()
283}
284
285/// How to round values halfway between two integer.
286#[derive(Copy, Clone, PartialEq, Eq)]
287enum Halfway {
288    /// Round away from zero.
289    AwayFromZero,
290
291    /// Round to even.
292    Even,
293}
294
295fn round_inner(value: i128, scale: i32, n: i32, halfway: Halfway) -> Option<i128> {
296    let position = scale.saturating_sub(n);
297    if position <= 0 {
298        Some(value)
299    } else if position < scale {
300        let divisor = pow10(position as usize);
301        let quotient = value / divisor;
302        let remainder = value % divisor;
303        let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
304            Ordering::Less => false,
305            Ordering::Equal => match halfway {
306                Halfway::AwayFromZero => true,
307                Halfway::Even => (quotient % 2) != 0,
308            },
309            Ordering::Greater => true,
310        };
311        let rounded_quotient = if round_away_from_zero {
312            quotient + quotient.signum()
313        } else {
314            quotient
315        };
316        Some(divisor * rounded_quotient)
317    } else if position > scale || value.abs() >= 5 * pow10(scale as usize - 1) {
318        Some(0)
319    } else {
320        None
321    }
322}
323
324/// Returns `floor(x / y)`.  This is copied out of `i128::div_floor` in the
325/// standard library, which is not yet stable.
326const fn div_floor(x: i128, y: i128) -> i128 {
327    let d = x / y;
328    let r = x % y;
329
330    // If the remainder is non-zero, we need to subtract one if the
331    // signs of lhs and rhs differ, as this means we rounded upwards
332    // instead of downwards. We do this branchlessly by creating a mask
333    // which is all-ones iff the signs differ, and 0 otherwise. Then by
334    // adding this mask (which corresponds to the signed value -1), we
335    // get our correction.
336    let correction = (x ^ y) >> (i128::BITS - 1);
337    if r != 0 {
338        d + correction
339    } else {
340        d
341    }
342}
343
344/// Returns `ceil(x / y)`.  This is copied out of `i128::div_ceil` in the
345/// standard library, which is not yet stable.
346const fn div_ceil(x: i128, y: i128) -> i128 {
347    let d = x / y;
348    let r = x % y;
349
350    // When remainder is non-zero we have a.div_ceil(b) == 1 + a.div_floor(b),
351    // so we can re-use the algorithm from div_floor, just adding 1.
352    let correction = 1 + ((x ^ y) >> (i128::BITS - 1));
353    if r != 0 {
354        d + correction
355    } else {
356        d
357    }
358}
359
360/// Returns `value * 10**exponent`, rounding to even if `exponent` is negative,
361/// or `None` if the result would be out of range for `i128`.
362fn i128_mul_pow10_round_even(value: i128, exponent: i32) -> Option<i128> {
363    Some(match exponent.cmp(&0) {
364        Ordering::Less => {
365            // Divide by a negative exponent.
366            if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
367                // Round toward even.
368                //
369                // For negative `x` and positive `y`, `x / y` rounds toward 0
370                // and `x % y` is zero or negative.
371                debug_assert!(divisor >= 2);
372                let quotient = value / divisor;
373                let remainder = value % divisor;
374                let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
375                    Ordering::Less => false,
376                    Ordering::Equal => (quotient % 2) != 0,
377                    Ordering::Greater => true,
378                };
379                if round_away_from_zero {
380                    quotient + quotient.signum()
381                } else {
382                    quotient
383                }
384            } else {
385                // `10**-exponent` is greater than `i128::MAX`.  The result
386                // must be zero.
387                0
388            }
389        }
390        Ordering::Equal => value,
391        Ordering::Greater => {
392            // Multiply by a positive exponent.
393            value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
394        }
395    })
396}
397
398/// This is a doc-test to check that trying to instantiate the value 1 for a
399/// type that can't represent it properly fails, with an error like "all values
400/// of Fixed::<S,P>::one() for S >= P have magnitude less than one"
401///
402/// ```compile_fail
403/// use feldera_fxp::Fixed;
404///
405/// let _ = Fixed::<5,5>::ONE;
406/// ```
407fn _invalid_constant_test() {}
408
409#[cfg(test)]
410mod test {
411    use crate::{DynamicDecimal, Fixed, ParseDecimalError};
412    use std::fmt::Write;
413
414    #[test]
415    fn from_str() {
416        for (s, expect) in [
417            ("0", Ok(0.0)),
418            ("0.", Ok(0.0)),
419            (".0", Ok(0.0)),
420            ("-0", Ok(-0.0)),
421            ("+0", Ok(-0.0)),
422            ("--0", Err(ParseDecimalError::SyntaxError)),
423            ("-+0", Err(ParseDecimalError::SyntaxError)),
424            ("0x", Err(ParseDecimalError::SyntaxError)),
425            ("0e5x", Err(ParseDecimalError::SyntaxError)),
426            ("1.23", Ok(1.23)),
427            ("-1.23", Ok(-1.23)),
428            ("+1.23", Ok(1.23)),
429            ("99999999", Ok(9999_9999.0)),
430            ("999999999", Err(ParseDecimalError::OutOfRange)),
431            ("999999999E-1", Ok(9999_9999.9)),
432            ("9999999999e-1", Err(ParseDecimalError::OutOfRange)),
433            ("9999999999E-2", Ok(9999_9999.99)),
434            ("99999999999e-2", Err(ParseDecimalError::OutOfRange)),
435            // This fails to parse because `99999999.999` rounds up to
436            // `100000000000`, which is out of range.
437            ("99999999999e-3", Err(ParseDecimalError::OutOfRange)),
438            // But with a `1` at the end rounds down, so it stays in range.
439            ("99999999991e-3", Ok(9999_9999.99)),
440            // This value overflows the range of `i128` as an integer, so it
441            // triggers the case where we stop accepting digits and simply
442            // adjust the exponent instead.
443            (
444                "111111111111111111111111111111111111111111e-34",
445                Ok(1111_1111.11),
446            ),
447            // This value overflows the range of `i128` in the fraction, so it
448            // triggers the case where we stop accepting digits and simply
449            // adjust the exponent instead.
450            (
451                "1.23456788901234567890123456789012345678890123456",
452                Ok(1.23),
453            ),
454            // This value positively overflows the exponent.
455            ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
456            // This value positively overflows the exponent but the value is 0.
457            ("0e999999999999999", Ok(0.0)),
458            // This value negatively overflows the exponent.
459            ("1e-999999999999999", Ok(0.0)),
460            // This value overflows the range of `i128` as an integer, which
461            // starts adjusting the exponent, and then it overflows the exponent
462            // with `e`.
463            (
464                "111111111111111111111111111111111111111111e2147483644",
465                Err(ParseDecimalError::OutOfRange),
466            ),
467            // This value adjusts the exponent downward, and then it negatively
468            // overflows the exponent with `e`.
469            (
470                ".1111111111111111111111111111111111111111e-2147483648",
471                Ok(0.0),
472            ),
473            ("123e5", Ok(12_300_000.0)),
474            ("123E4", Ok(1_230_000.0)),
475            ("123e3", Ok(123_000.0)),
476            ("123e2", Ok(12_300.0)),
477            ("123e1", Ok(1_230.0)),
478            ("123e0", Ok(123.0)),
479            ("123e-1", Ok(12.3)),
480            ("123e-2", Ok(1.23)),
481            (".123", Ok(0.12)),
482            (".124", Ok(0.12)),
483            (".125", Ok(0.12)),
484            (".126", Ok(0.13)),
485            (".133", Ok(0.13)),
486            (".134", Ok(0.13)),
487            (".135", Ok(0.14)),
488            (".136", Ok(0.14)),
489        ] {
490            println!("{s}: {:?}", s.parse::<F>());
491            assert_eq!(s.parse::<F>(), expect.map(f));
492        }
493    }
494
495    #[test]
496    fn debug() {
497        fn test<const P: usize, const S: usize>(fixed: Fixed<P, S>, expect: &str) {
498            assert_eq!(format!("{fixed:?}"), expect);
499            let dynamic = DynamicDecimal::from(fixed);
500            assert_eq!(format!("{dynamic:?}"), expect);
501        }
502        test(Fixed::<20, 7>::try_from(0).unwrap(), "0");
503        test(Fixed::<20, 7>::try_from(5).unwrap(), "5");
504        test(Fixed::<20, 7>::try_from(-5).unwrap(), "-5");
505        test(Fixed::<20, 7>::try_from(10).unwrap(), "10");
506        test(Fixed::<20, 7>::try_from(0.0001).unwrap(), "0.0001");
507        test(Fixed::<20, 7>::try_from(-0.0001).unwrap(), "-0.0001");
508        test(Fixed::<20, 7>::try_from(1.0001).unwrap(), "1.0001");
509        test(Fixed::<20, 7>::try_from(-1.0001).unwrap(), "-1.0001");
510        test(Fixed::<20, 7>::try_from(1.682501).unwrap(), "1.682501");
511        test(Fixed::<20, 4>::try_from(1.6825).unwrap(), "1.6825");
512        test(Fixed::<20, 6>::try_from(1.995670).unwrap(), "1.99567");
513        test(Fixed::<20, 6>::try_from(0.995670).unwrap(), "0.99567");
514        test(Fixed::<6, 6>::try_from(0.995670).unwrap(), "0.99567");
515
516        test(Fixed::<20, 7>::try_from(-1.682501).unwrap(), "-1.682501");
517        test(Fixed::<20, 4>::try_from(-1.6825).unwrap(), "-1.6825");
518        test(Fixed::<20, 6>::try_from(-1.995670).unwrap(), "-1.99567");
519        test(Fixed::<20, 6>::try_from(-0.995670).unwrap(), "-0.99567");
520    }
521
522    #[test]
523    fn display() {
524        fn test<const P: usize, const S: usize>(fixed: Fixed<P, S>, expect: &str) {
525            let mut s = String::new();
526            write!(&mut s, "{fixed}").unwrap();
527            for precision in 0..=S + 1 {
528                write!(&mut s, " {fixed:.0$}", precision).unwrap();
529            }
530            assert_eq!(s, expect);
531
532            let dynamic = DynamicDecimal::from(fixed);
533            let mut s = String::new();
534            write!(&mut s, "{dynamic}").unwrap();
535            for precision in 0..=S + 1 {
536                write!(&mut s, " {dynamic:.0$}", precision).unwrap();
537            }
538            assert_eq!(s, expect);
539        }
540
541        test(
542            Fixed::<20, 7>::try_from(0.0001).unwrap(),
543            "0.0001 0 0.0 0.00 0.000 0.0001 0.00010 0.000100 0.0001000 0.00010000",
544        );
545        test(
546            Fixed::<20, 7>::try_from(-0.0001).unwrap(),
547            "-0.0001 -0 -0.0 -0.00 -0.000 -0.0001 -0.00010 -0.000100 -0.0001000 -0.00010000",
548        );
549        test(
550            Fixed::<20, 7>::try_from(1.0001).unwrap(),
551            "1.0001 1 1.0 1.00 1.000 1.0001 1.00010 1.000100 1.0001000 1.00010000",
552        );
553        test(
554            Fixed::<20, 7>::try_from(-1.0001).unwrap(),
555            "-1.0001 -1 -1.0 -1.00 -1.000 -1.0001 -1.00010 -1.000100 -1.0001000 -1.00010000",
556        );
557        test(
558            Fixed::<20, 7>::try_from(1.682501).unwrap(),
559            "1.682501 2 1.7 1.68 1.683 1.6825 1.68250 1.682501 1.6825010 1.68250100",
560        );
561        test(
562            Fixed::<20, 4>::try_from(1.6825).unwrap(),
563            "1.6825 2 1.7 1.68 1.682 1.6825 1.68250",
564        );
565        test(
566            Fixed::<20, 6>::try_from(1.995670).unwrap(),
567            "1.99567 2 2.0 2.00 1.996 1.9957 1.99567 1.995670 1.9956700",
568        );
569        test(
570            Fixed::<20, 6>::try_from(0.995670).unwrap(),
571            "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700",
572        );
573        test(
574            Fixed::<6, 6>::try_from(0.995670).unwrap(),
575            "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700",
576        );
577
578        test(
579            Fixed::<20, 7>::try_from(-1.682501).unwrap(),
580            "-1.682501 -2 -1.7 -1.68 -1.683 -1.6825 -1.68250 -1.682501 -1.6825010 -1.68250100",
581        );
582        test(
583            Fixed::<20, 4>::try_from(-1.6825).unwrap(),
584            "-1.6825 -2 -1.7 -1.68 -1.682 -1.6825 -1.68250",
585        );
586        test(
587            Fixed::<20, 6>::try_from(-1.995670).unwrap(),
588            "-1.99567 -2 -2.0 -2.00 -1.996 -1.9957 -1.99567 -1.995670 -1.9956700",
589        );
590        test(
591            Fixed::<20, 6>::try_from(-0.995670).unwrap(),
592            "-0.99567 -1 -1.0 -1.00 -0.996 -0.9957 -0.99567 -0.995670 -0.9956700",
593        );
594    }
595
596    type F = Fixed<10, 2>;
597    fn f(n: f64) -> F {
598        Fixed::try_from(n).unwrap()
599    }
600}