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
265impl std::fmt::Display for ParseDecimalError {
266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
267        let message = match self {
268            ParseDecimalError::OutOfRange => "Value out of range",
269            ParseDecimalError::SyntaxError => "Syntax error in numeric value",
270        };
271        f.write_str(message)
272    }
273}
274
275/// Error returned for operations that would produce an out-of-range result.
276#[derive(Copy, Clone, Debug, PartialEq, Eq)]
277pub struct OutOfRange;
278
279impl std::fmt::Display for OutOfRange {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
281        std::fmt::Display::fmt(&"Value out of range", f)
282    }
283}
284
285/// Returns `10**exponent`, or `None` if `exponent > 38` (because the result
286/// would be greater than `i128::MAX`).
287const fn checked_pow10(exponent: u32) -> Option<i128> {
288    10i128.checked_pow(exponent)
289}
290
291/// Returns `10**exponent`.
292///
293/// # Panic
294///
295/// Panics if `exponent > 38` (because the result would be greater than
296/// `i128::MAX`).
297pub const fn pow10(exponent: usize) -> i128 {
298    10i128.checked_pow(exponent as u32).unwrap()
299}
300
301/// How to round values halfway between two integer.
302#[derive(Copy, Clone, PartialEq, Eq)]
303enum Halfway {
304    /// Round away from zero.
305    AwayFromZero,
306
307    /// Round to even.
308    Even,
309}
310
311fn round_inner(value: i128, scale: i32, n: i32, halfway: Halfway) -> Option<i128> {
312    let position = scale.saturating_sub(n);
313    if position <= 0 {
314        Some(value)
315    } else if value.abs() < 5 * pow10(position as usize - 1) {
316        Some(0)
317    } else {
318        let divisor = pow10(position as usize);
319        let quotient = value / divisor;
320        let remainder = value % divisor;
321        let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
322            Ordering::Less => false,
323            Ordering::Equal => match halfway {
324                Halfway::AwayFromZero => true,
325                Halfway::Even => (quotient % 2) != 0,
326            },
327            Ordering::Greater => true,
328        };
329        let rounded_quotient = if round_away_from_zero {
330            quotient + value.signum()
331        } else {
332            quotient
333        };
334        // println!("quotient={quotient}, divisor={divisor}, remainder={remainder}, raz={round_away_from_zero}, rounded_quotient={rounded_quotient}");
335        divisor.checked_mul(rounded_quotient)
336    }
337}
338
339/// Returns `floor(x / y)`.  This is copied out of `i128::div_floor` in the
340/// standard library, which is not yet stable.
341const fn div_floor(x: i128, y: i128) -> i128 {
342    let d = x / y;
343    let r = x % y;
344
345    // If the remainder is non-zero, we need to subtract one if the
346    // signs of lhs and rhs differ, as this means we rounded upwards
347    // instead of downwards. We do this branchlessly by creating a mask
348    // which is all-ones iff the signs differ, and 0 otherwise. Then by
349    // adding this mask (which corresponds to the signed value -1), we
350    // get our correction.
351    let correction = (x ^ y) >> (i128::BITS - 1);
352    if r != 0 {
353        d + correction
354    } else {
355        d
356    }
357}
358
359/// Returns `ceil(x / y)`.  This is copied out of `i128::div_ceil` in the
360/// standard library, which is not yet stable.
361const fn div_ceil(x: i128, y: i128) -> i128 {
362    let d = x / y;
363    let r = x % y;
364
365    // When remainder is non-zero we have a.div_ceil(b) == 1 + a.div_floor(b),
366    // so we can re-use the algorithm from div_floor, just adding 1.
367    let correction = 1 + ((x ^ y) >> (i128::BITS - 1));
368    if r != 0 {
369        d + correction
370    } else {
371        d
372    }
373}
374
375/// Returns `value * 10**exponent`, rounding to even if `exponent` is negative,
376/// or `None` if the result would be out of range for `i128`.
377fn i128_mul_pow10_round_even(value: i128, exponent: i32) -> Option<i128> {
378    Some(match exponent.cmp(&0) {
379        Ordering::Less => {
380            // Divide by a negative exponent.
381            if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
382                // Round toward even.
383                //
384                // For negative `x` and positive `y`, `x / y` rounds toward 0
385                // and `x % y` is zero or negative.
386                debug_assert!(divisor >= 2);
387                let quotient = value / divisor;
388                let remainder = value % divisor;
389                let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
390                    Ordering::Less => false,
391                    Ordering::Equal => (quotient % 2) != 0,
392                    Ordering::Greater => true,
393                };
394                if round_away_from_zero {
395                    quotient + quotient.signum()
396                } else {
397                    quotient
398                }
399            } else {
400                // `10**-exponent` is greater than `i128::MAX`.  The result
401                // must be zero.
402                0
403            }
404        }
405        Ordering::Equal => value,
406        Ordering::Greater => {
407            // Multiply by a positive exponent.
408            value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
409        }
410    })
411}
412
413/// This is a doc-test to check that trying to instantiate the value 1 for a
414/// type that can't represent it properly fails, with an error like "all values
415/// of Fixed::<S,P>::one() for S >= P have magnitude less than one"
416///
417/// ```compile_fail
418/// use feldera_fxp::Fixed;
419///
420/// let _ = Fixed::<5,5>::ONE;
421/// ```
422fn _invalid_constant_test() {}
423
424#[cfg(test)]
425mod test {
426    use crate::{DynamicDecimal, Fixed, ParseDecimalError};
427    use std::fmt::Write;
428
429    #[test]
430    fn from_str() {
431        for (s, expect) in [
432            ("0", Ok(0.0)),
433            ("0.", Ok(0.0)),
434            (".0", Ok(0.0)),
435            ("-0", Ok(-0.0)),
436            ("+0", Ok(-0.0)),
437            ("--0", Err(ParseDecimalError::SyntaxError)),
438            ("-+0", Err(ParseDecimalError::SyntaxError)),
439            ("0x", Err(ParseDecimalError::SyntaxError)),
440            ("0e5x", Err(ParseDecimalError::SyntaxError)),
441            ("1.23", Ok(1.23)),
442            ("-1.23", Ok(-1.23)),
443            ("+1.23", Ok(1.23)),
444            ("99999999", Ok(9999_9999.0)),
445            ("999999999", Err(ParseDecimalError::OutOfRange)),
446            ("999999999E-1", Ok(9999_9999.9)),
447            ("9999999999e-1", Err(ParseDecimalError::OutOfRange)),
448            ("9999999999E-2", Ok(9999_9999.99)),
449            ("99999999999e-2", Err(ParseDecimalError::OutOfRange)),
450            // This fails to parse because `99999999.999` rounds up to
451            // `100000000000`, which is out of range.
452            ("99999999999e-3", Err(ParseDecimalError::OutOfRange)),
453            // But with a `1` at the end rounds down, so it stays in range.
454            ("99999999991e-3", Ok(9999_9999.99)),
455            // This value overflows the range of `i128` as an integer, so it
456            // triggers the case where we stop accepting digits and simply
457            // adjust the exponent instead.
458            (
459                "111111111111111111111111111111111111111111e-34",
460                Ok(1111_1111.11),
461            ),
462            // This value overflows the range of `i128` in the fraction, so it
463            // triggers the case where we stop accepting digits and simply
464            // adjust the exponent instead.
465            (
466                "1.23456788901234567890123456789012345678890123456",
467                Ok(1.23),
468            ),
469            // This value positively overflows the exponent.
470            ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
471            // This value positively overflows the exponent but the value is 0.
472            ("0e999999999999999", Ok(0.0)),
473            // This value negatively overflows the exponent.
474            ("1e-999999999999999", Ok(0.0)),
475            // This value overflows the range of `i128` as an integer, which
476            // starts adjusting the exponent, and then it overflows the exponent
477            // with `e`.
478            (
479                "111111111111111111111111111111111111111111e2147483644",
480                Err(ParseDecimalError::OutOfRange),
481            ),
482            // This value adjusts the exponent downward, and then it negatively
483            // overflows the exponent with `e`.
484            (
485                ".1111111111111111111111111111111111111111e-2147483648",
486                Ok(0.0),
487            ),
488            ("123e5", Ok(12_300_000.0)),
489            ("123E4", Ok(1_230_000.0)),
490            ("123e3", Ok(123_000.0)),
491            ("123e2", Ok(12_300.0)),
492            ("123e1", Ok(1_230.0)),
493            ("123e0", Ok(123.0)),
494            ("123e-1", Ok(12.3)),
495            ("123e-2", Ok(1.23)),
496            (".123", Ok(0.12)),
497            (".124", Ok(0.12)),
498            (".125", Ok(0.12)),
499            (".126", Ok(0.13)),
500            (".133", Ok(0.13)),
501            (".134", Ok(0.13)),
502            (".135", Ok(0.14)),
503            (".136", Ok(0.14)),
504        ] {
505            println!("{s}: {:?}", s.parse::<F>());
506            assert_eq!(s.parse::<F>(), expect.map(f));
507        }
508    }
509
510    #[test]
511    fn debug() {
512        fn test<const P: usize, const S: usize>(fixed: Fixed<P, S>, expect: &str) {
513            assert_eq!(format!("{fixed:?}"), expect);
514            let dynamic = DynamicDecimal::from(fixed);
515            assert_eq!(format!("{dynamic:?}"), expect);
516        }
517        test(Fixed::<20, 7>::try_from(0).unwrap(), "0");
518        test(Fixed::<20, 7>::try_from(5).unwrap(), "5");
519        test(Fixed::<20, 7>::try_from(-5).unwrap(), "-5");
520        test(Fixed::<20, 7>::try_from(10).unwrap(), "10");
521        test(Fixed::<20, 7>::try_from(0.0001).unwrap(), "0.0001");
522        test(Fixed::<20, 7>::try_from(-0.0001).unwrap(), "-0.0001");
523        test(Fixed::<20, 7>::try_from(1.0001).unwrap(), "1.0001");
524        test(Fixed::<20, 7>::try_from(-1.0001).unwrap(), "-1.0001");
525        test(Fixed::<20, 7>::try_from(1.682501).unwrap(), "1.682501");
526        test(Fixed::<20, 4>::try_from(1.6825).unwrap(), "1.6825");
527        test(Fixed::<20, 6>::try_from(1.995670).unwrap(), "1.99567");
528        test(Fixed::<20, 6>::try_from(0.995670).unwrap(), "0.99567");
529        test(Fixed::<6, 6>::try_from(0.995670).unwrap(), "0.99567");
530
531        test(Fixed::<20, 7>::try_from(-1.682501).unwrap(), "-1.682501");
532        test(Fixed::<20, 4>::try_from(-1.6825).unwrap(), "-1.6825");
533        test(Fixed::<20, 6>::try_from(-1.995670).unwrap(), "-1.99567");
534        test(Fixed::<20, 6>::try_from(-0.995670).unwrap(), "-0.99567");
535    }
536
537    #[test]
538    fn display() {
539        fn test<const P: usize, const S: usize>(fixed: Fixed<P, S>, expect: &str) {
540            let mut s = String::new();
541            write!(&mut s, "{fixed}").unwrap();
542            for precision in 0..=S + 1 {
543                write!(&mut s, " {fixed:.0$}", precision).unwrap();
544            }
545            assert_eq!(s, expect);
546
547            let dynamic = DynamicDecimal::from(fixed);
548            let mut s = String::new();
549            write!(&mut s, "{dynamic}").unwrap();
550            for precision in 0..=S + 1 {
551                write!(&mut s, " {dynamic:.0$}", precision).unwrap();
552            }
553            assert_eq!(s, expect);
554        }
555
556        test(
557            Fixed::<20, 7>::try_from(0.0001).unwrap(),
558            "0.0001 0 0.0 0.00 0.000 0.0001 0.00010 0.000100 0.0001000 0.00010000",
559        );
560        test(
561            Fixed::<20, 7>::try_from(-0.0001).unwrap(),
562            "-0.0001 -0 -0.0 -0.00 -0.000 -0.0001 -0.00010 -0.000100 -0.0001000 -0.00010000",
563        );
564        test(
565            Fixed::<20, 7>::try_from(1.0001).unwrap(),
566            "1.0001 1 1.0 1.00 1.000 1.0001 1.00010 1.000100 1.0001000 1.00010000",
567        );
568        test(
569            Fixed::<20, 7>::try_from(-1.0001).unwrap(),
570            "-1.0001 -1 -1.0 -1.00 -1.000 -1.0001 -1.00010 -1.000100 -1.0001000 -1.00010000",
571        );
572        test(
573            Fixed::<20, 7>::try_from(1.682501).unwrap(),
574            "1.682501 2 1.7 1.68 1.683 1.6825 1.68250 1.682501 1.6825010 1.68250100",
575        );
576        test(
577            Fixed::<20, 4>::try_from(1.6825).unwrap(),
578            "1.6825 2 1.7 1.68 1.682 1.6825 1.68250",
579        );
580        test(
581            Fixed::<20, 6>::try_from(1.995670).unwrap(),
582            "1.99567 2 2.0 2.00 1.996 1.9957 1.99567 1.995670 1.9956700",
583        );
584        test(
585            Fixed::<20, 6>::try_from(0.995670).unwrap(),
586            "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700",
587        );
588        test(
589            Fixed::<6, 6>::try_from(0.995670).unwrap(),
590            "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700",
591        );
592
593        test(
594            Fixed::<20, 7>::try_from(-1.682501).unwrap(),
595            "-1.682501 -2 -1.7 -1.68 -1.683 -1.6825 -1.68250 -1.682501 -1.6825010 -1.68250100",
596        );
597        test(
598            Fixed::<20, 4>::try_from(-1.6825).unwrap(),
599            "-1.6825 -2 -1.7 -1.68 -1.682 -1.6825 -1.68250",
600        );
601        test(
602            Fixed::<20, 6>::try_from(-1.995670).unwrap(),
603            "-1.99567 -2 -2.0 -2.00 -1.996 -1.9957 -1.99567 -1.995670 -1.9956700",
604        );
605        test(
606            Fixed::<20, 6>::try_from(-0.995670).unwrap(),
607            "-0.99567 -1 -1.0 -1.00 -0.996 -0.9957 -0.99567 -0.995670 -0.9956700",
608        );
609    }
610
611    type F = Fixed<10, 2>;
612    fn f(n: f64) -> F {
613        Fixed::try_from(n).unwrap()
614    }
615}