Skip to main content

feldera_fxp/
dynamic.rs

1use std::{
2    cmp::Ordering,
3    fmt::{Debug, Display},
4    ops::{Add, Div, Mul, Neg, Rem, Sub},
5    str::FromStr,
6};
7
8use crate::{
9    Fixed, OutOfRange, ParseDecimalError, checked_pow10, debug_decimal, display_decimal,
10    parse_decimal, pow10, u256::I256,
11};
12
13use num_traits::{CheckedDiv, CheckedMul};
14use rand::Rng;
15use rand::distributions::uniform::{UniformInt, UniformSampler};
16
17/// Decimal real number with 38 digits of precision and dynamic scale.
18///
19/// This type is primarily meant as a serialized form of `Fixed` that does not
20/// require parameterization.  Any `Fixed` can be converted into
21/// `DynamicDecimal` and then converted back into any other `Fixed`, possibly
22/// with a different precision and scale, without loss of precision (beyond that
23/// inherent in change of scale, if any).
24///
25/// # Representation
26///
27/// The number is represented as an `i128` significand and a `u8` scale, that
28/// together express the value `significand * 10**-scale`.
29///
30/// # Invariants
31///
32/// These invariants on significand and scale ensure that the value is in
33/// canonical form:
34///
35/// * If `significand != 0 && scale != 0`, then `significand` must not be a
36///   multiple of 10.
37///
38/// * If `significand != 0 && scale == 0`, then `significand` may be a
39///   multiple of 10.  (This is a "denormalized" representation with fewer
40///   digits of precision than other forms.)
41///
42/// * If `significand == 0`, then `scale` must be zero.
43///
44/// # Arithmetic
45///
46/// There are various arithmetic traits implemented for DynamicDecimal,
47/// but they are intended for limited uses; in particular, these
48/// functions will panic for overflows.
49#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
50#[cfg_attr(feature = "size_of", derive(size_of::SizeOf))]
51#[cfg_attr(
52    feature = "rkyv",
53    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
54)]
55pub struct DynamicDecimal {
56    /// Significand.
57    sig: i128,
58
59    /// The number of digits of the value that follow the decimal point.
60    exponent: u8,
61}
62
63impl DynamicDecimal {
64    /// The largest `DynamicDecimal` value (`i128::MAX`).
65    pub const MAX: Self = DynamicDecimal::new(i128::MAX, 0);
66
67    /// The smallest `DynamicDecimal` value (`i128::MIN`).
68    pub const MIN: Self = DynamicDecimal::new(i128::MIN, 0);
69
70    /// 0 as `DynamicDecimal`.
71    pub const ZERO: Self = DynamicDecimal::new(0, 0);
72
73    /// 1 as `DynamicDecimal`.
74    pub const ONE: Self = DynamicDecimal::new(1, 0);
75
76    /// Constructs a new `DynamicDecimal` with value `sig * 10**-exponent`.
77    pub const fn new(sig: i128, exponent: u8) -> Self {
78        if exponent == 0 {
79            Self { sig, exponent }
80        } else if sig == 0 {
81            Self { sig, exponent: 0 }
82        } else {
83            /// Returns `(sig, exponent)` divided by `10**D` as many times as
84            /// possible without dropping nonzero decimal digits.
85            const fn reduce<const D: u8>(mut sig: i128, mut exponent: u8) -> (i128, u8) {
86                // `10**D`.
87                let scale = pow10(D as usize);
88
89                // A multiple of `10**D` has at least `D` trailing zeros, since
90                // `10 == 2*5`, so if any of the `D` trailing bits is nonzero,
91                // we can skip the expensive remainder operation.
92                while exponent >= D
93                    && sig.unsigned_abs() >= scale.cast_unsigned()
94                    && (sig & ((1 << D) - 1)) == 0
95                    && sig % scale == 0
96                {
97                    sig /= scale;
98                    exponent -= D;
99                }
100                (sig, exponent)
101            }
102
103            // Canonicalize in a few stages, so that we don't have to divide as
104            // many times as otherwise for numbers that have many trailing
105            // decimal zeros.
106            let (sig, exponent) = reduce::<8>(sig, exponent);
107            let (sig, exponent) = reduce::<4>(sig, exponent);
108            let (sig, exponent) = reduce::<1>(sig, exponent);
109            debug_assert!(sig % 10 != 0 || exponent == 0);
110            Self { sig, exponent }
111        }
112    }
113
114    /// Returns the canonical [significand](Self#representation).
115    pub const fn significand(&self) -> i128 {
116        self.sig
117    }
118
119    /// Returns the canonical [scale](Self#representation).
120    pub const fn exponent(&self) -> u8 {
121        self.exponent
122    }
123
124    /// Truncates the value to an integer by discarding digits after decimal point
125    pub fn trunc(&self) -> Self {
126        DynamicDecimal::new(self.sig / pow10(self.exponent as usize), 0)
127    }
128
129    /// Returns this value, truncated toward zero at `digits` after the decimal
130    /// point.
131    pub fn trunc_digits(&self, digits: u8) -> Self {
132        if self.exponent() <= digits {
133            *self
134        } else if self.exponent - digits > 38 {
135            Self::ZERO
136        } else {
137            let divisor = pow10((self.exponent - digits) as usize);
138            Self::new(self.significand() / divisor, digits)
139        }
140    }
141
142    /// Floor of the value
143    pub fn floor(&self) -> Self {
144        let trunc = self.trunc();
145        if self.is_negative() {
146            if trunc != *self {
147                trunc - DynamicDecimal::new(1, 0)
148            } else {
149                *self
150            }
151        } else {
152            trunc
153        }
154    }
155
156    /// True if value is negative
157    pub const fn is_negative(self) -> bool {
158        self.sig.is_negative()
159    }
160
161    /// The absolute value
162    pub const fn abs(self) -> Self {
163        Self::new(self.sig.abs(), self.exponent)
164    }
165
166    /// Returns `sig * 10**-exponent`.  Drops the fractional digits past the
167    /// largest exponent.
168    fn from_wide_exponent(sig: i128, exponent: usize) -> Self {
169        let excess = exponent.saturating_sub(u8::MAX.into());
170        let sig = if excess > 38 { 0 } else { sig / pow10(excess) };
171        Self::new(sig, (exponent - excess) as u8)
172    }
173
174    /// Returns `value * 10**-exponent`, or `None` if the integer part does not
175    /// fit in the significand.  Drops the trailing digits of `value` that do
176    /// not fit in the significand, and the fractional digits past the largest
177    /// exponent.
178    fn checked_from_i256(value: I256, exponent: usize) -> Option<Self> {
179        let (sig, dropped) = value.reduce_to_i128();
180        let exponent = exponent.checked_sub(dropped)?;
181        Some(Self::from_wide_exponent(sig, exponent))
182    }
183
184    /// Returns `coarse + fine`, truncated toward zero, or `None` if the integer
185    /// part does not fit in the significand.  `fine` has more than 38
186    /// fractional digits more than `coarse`.
187    fn add_distant_exponents(coarse: Self, fine: Self) -> Option<Self> {
188        if coarse.sig == 0 {
189            return Some(fine);
190        }
191        // Keep the digits of `fine` down to 37 places past the last digit of
192        // `coarse`, and replace the digits past them by one digit with their
193        // sign.  The exact sum and this sum lie between the same two multiples
194        // of 10 in units of that digit, so both truncate to the same value once
195        // that digit is dropped.
196        let dropped = (fine.exponent - coarse.exponent) as usize - 37;
197        let (kept, rest) = if dropped > 38 {
198            (0, fine.sig)
199        } else {
200            (fine.sig / pow10(dropped), fine.sig % pow10(dropped))
201        };
202        let fine_sig = kept * 10 + rest.signum();
203        let sum = I256::from_product(coarse.sig, pow10(38)) + I256::from(fine_sig);
204        let (sig, dropped) = sum.reduce_to_i128();
205        // The last digit of `sum` stands for the dropped digits of `fine`
206        let (sig, dropped) = if dropped == 0 {
207            (sig / 10, 1)
208        } else {
209            (sig, dropped)
210        };
211        let exponent = (coarse.exponent as usize + 38).checked_sub(dropped)?;
212        Some(Self::from_wide_exponent(sig, exponent))
213    }
214
215    /// Deserializes [DynamicDecimal] into `Fixed`.  If successful, returns the
216    /// original value from before serialization.  If `S < value.exponent`, then
217    /// some trailing decimals are lost, by rounding toward even.  Returns an
218    /// error` if the value is out of range for this type.
219    #[doc(hidden)]
220    pub fn into_fixed_round_even<const P: usize, const S: usize>(
221        self,
222    ) -> Result<Fixed<P, S>, OutOfRange> {
223        Fixed::<P, S>::try_new_with_exponent_round_even(self.sig, S as i32 - self.exponent as i32)
224            .ok_or(OutOfRange)
225    }
226}
227
228impl<const P: usize, const S: usize> From<Fixed<P, S>> for DynamicDecimal {
229    /// Encodes `value`, for later deserialization into a new `Fixed` with
230    /// possibly a different precision and scale.
231    fn from(value: Fixed<P, S>) -> Self {
232        Self::new(value.0, S as u8)
233    }
234}
235
236impl Neg for DynamicDecimal {
237    type Output = Self;
238
239    fn neg(self) -> Self {
240        DynamicDecimal::new(-self.sig, self.exponent)
241    }
242}
243
244impl Add<DynamicDecimal> for DynamicDecimal {
245    type Output = Self;
246
247    fn add(self, other: Self) -> Self {
248        // `coarse` has fewer fractional digits, so it is scaled to the exponent of `fine`
249        let (coarse, fine) = if self.exponent <= other.exponent {
250            (self, other)
251        } else {
252            (other, self)
253        };
254        if fine.exponent - coarse.exponent > 38 {
255            return DynamicDecimal::add_distant_exponents(coarse, fine)
256                .unwrap_or_else(|| panic!("Overflow adding {} + {}", self, other));
257        }
258        let factor = pow10((fine.exponent - coarse.exponent) as usize);
259        let sum = coarse
260            .sig
261            .checked_mul(factor)
262            .and_then(|scaled| scaled.checked_add(fine.sig));
263        match sum {
264            Some(sum) => DynamicDecimal::new(sum, fine.exponent),
265            None => {
266                let sum = I256::from_product(coarse.sig, factor) + I256::from(fine.sig);
267                DynamicDecimal::checked_from_i256(sum, fine.exponent.into())
268                    .unwrap_or_else(|| panic!("Overflow adding {} + {}", self, other))
269            }
270        }
271    }
272}
273
274impl Sub<DynamicDecimal> for DynamicDecimal {
275    type Output = Self;
276
277    fn sub(self, other: Self) -> Self {
278        self.add(other.neg())
279    }
280}
281
282impl Mul<DynamicDecimal> for DynamicDecimal {
283    type Output = Self;
284
285    fn mul(self, other: Self) -> Self {
286        self.checked_mul(&other)
287            .unwrap_or_else(|| panic!("Overflow multiplying {} * {}", self, other))
288    }
289}
290
291impl CheckedMul for DynamicDecimal {
292    fn checked_mul(&self, other: &Self) -> Option<Self> {
293        let product = I256::from_product(self.sig, other.sig);
294        // The exponent of a product is the sum of the exponents.
295        let exponent = self.exponent as usize + other.exponent as usize;
296        DynamicDecimal::checked_from_i256(product, exponent)
297    }
298}
299
300impl CheckedDiv for DynamicDecimal {
301    fn checked_div(&self, other: &DynamicDecimal) -> Option<DynamicDecimal> {
302        if other.sig == 0i128 {
303            None
304        } else {
305            // We have to choose an arbitrary number of digits after the decimal
306            // point where we stop.
307            const MIN_DIGITS: u8 = 6;
308            let digits = std::cmp::max(std::cmp::max(MIN_DIGITS, self.exponent), other.exponent);
309
310            let shift_left = (other.exponent + digits).saturating_sub(self.exponent);
311            if shift_left > 38 {
312                // A shift this big would exceed the range of I256, so we can't
313                // calculate it, but the ultimate result would also overflow, so
314                // we don't have to.
315                None
316            } else {
317                let scaled = I256::from_product(self.sig, pow10(shift_left as usize));
318                let div = scaled.narrowing_div(other.sig).unwrap();
319                let exp = self.exponent.saturating_sub(other.exponent + digits);
320                let adjust = div * pow10(exp as usize);
321                Some(DynamicDecimal::new(adjust, digits))
322            }
323        }
324    }
325}
326
327impl Div<DynamicDecimal> for DynamicDecimal {
328    type Output = Self;
329
330    fn div(self, other: DynamicDecimal) -> DynamicDecimal {
331        match self.checked_div(&other) {
332            None => panic!("Overflow dividing {} / {}", self, other),
333            Some(v) => v,
334        }
335    }
336}
337
338impl Rem<DynamicDecimal> for DynamicDecimal {
339    type Output = Self;
340
341    fn rem(self, other: Self) -> Self {
342        let neg = self.is_negative();
343        let left = self.abs();
344        let right = other.abs();
345        let div = left.div(right);
346        let trunc = div.trunc();
347        let mul = right.mul(trunc);
348        let rem = left.sub(mul);
349        if neg { rem.neg() } else { rem }
350    }
351}
352
353impl<const P: usize, const S: usize> TryFrom<DynamicDecimal> for Fixed<P, S> {
354    type Error = OutOfRange;
355
356    /// Deserializes [DynamicDecimal] into `Fixed`.  If successful, returns the
357    /// original value from before serialization.  If `S < value.exponent`, then
358    /// some trailing decimals are lost, by rounding toward zero.  Returns an
359    /// error` if the value is out of range for this type.
360    fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
361        Self::try_new_with_exponent(value.sig, S as i32 - value.exponent as i32).ok_or(OutOfRange)
362    }
363}
364
365impl Debug for DynamicDecimal {
366    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
367        debug_decimal(self.sig, self.exponent as usize, f)
368    }
369}
370
371impl Display for DynamicDecimal {
372    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        display_decimal(self.sig, self.exponent as usize, f)
374    }
375}
376
377impl FromStr for DynamicDecimal {
378    type Err = ParseDecimalError;
379
380    /// Parses `s` as `DynamicDecimal`.
381    ///
382    /// This accepts the same forms as [f64::from_str], except that it rejects
383    /// infinities and NaNs (which `Fixed` does not support), as well as
384    /// out-of-range values.  Rounds overprecise values to the nearest
385    /// representable value, rounding halfway values to even.
386    fn from_str(s: &str) -> Result<Self, Self::Err> {
387        let (sig, exponent) = parse_decimal(s, 0)?;
388        match (sig, exponent) {
389            (0, _) => Ok(Self::ZERO),
390            (_, 1..) => {
391                let sig = checked_pow10(exponent.cast_unsigned())
392                    .and_then(|m| m.checked_mul(sig))
393                    .ok_or(ParseDecimalError::OutOfRange)?;
394                Ok(Self::new(sig, 0))
395            }
396            (_, 0) => Ok(Self { sig, exponent: 0 }),
397            (_, -255..0) => Ok(Self::new(sig, (-exponent) as u8)),
398            (_, ..-255) => {
399                // We could "denormalize" by dividing `sig` by a power of 10 and
400                // adjusting `exponent`, but the value would inevitably be zero
401                // when we convert to `Fixed`, which is what we really care
402                // about.
403                Ok(Self::ZERO)
404            }
405        }
406    }
407}
408
409impl TryFrom<u128> for DynamicDecimal {
410    type Error = OutOfRange;
411
412    fn try_from(value: u128) -> Result<Self, Self::Error> {
413        Ok(Self::new(value.try_into().map_err(|_| OutOfRange)?, 0))
414    }
415}
416
417macro_rules! from_int {
418    ($type_name:ty) => {
419        impl From<$type_name> for DynamicDecimal {
420            fn from(value: $type_name) -> Self {
421                Self::new(value as i128, 0)
422            }
423        }
424    };
425}
426from_int!(i128);
427from_int!(i64);
428from_int!(i32);
429from_int!(i16);
430from_int!(i8);
431from_int!(isize);
432from_int!(u64);
433from_int!(u32);
434from_int!(u16);
435from_int!(u8);
436from_int!(usize);
437
438impl From<DynamicDecimal> for i128 {
439    /// Convert from `Fixed` to integer, rounding toward zero (the same
440    /// semantics as Rust casts from float to integer).
441    fn from(value: DynamicDecimal) -> Self {
442        checked_pow10(value.exponent.into()).map_or(0, |divisor| value.sig / divisor)
443    }
444}
445
446macro_rules! try_to_signed_int {
447    ($type_name:ty) => {
448        impl TryFrom<DynamicDecimal> for $type_name {
449            type Error = OutOfRange;
450
451            /// Convert from `Fixed` to integer, rounding toward zero (the same
452            /// semantics as Rust casts from float to integer).
453            fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
454                match checked_pow10(value.exponent.into()) {
455                    Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
456                    None => Ok(0),
457                }
458            }
459        }
460    };
461}
462try_to_signed_int!(i64);
463try_to_signed_int!(i32);
464try_to_signed_int!(i16);
465try_to_signed_int!(i8);
466try_to_signed_int!(isize);
467
468/// This is the same as [try_to_signed_int] except for the documentation
469/// comment.
470macro_rules! try_to_unsigned_int {
471    ($type_name:ty) => {
472        impl TryFrom<DynamicDecimal> for $type_name {
473            type Error = OutOfRange;
474
475            /// Convert from `Fixed` to integer, rounding toward zero (the same
476            /// semantics as Rust casts from float to integer).
477            ///
478            /// Because this rounds toward zero, negative values greater than -1
479            /// will convert to 0 instead of an out-of-range error.
480            fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
481                match checked_pow10(value.exponent.into()) {
482                    Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
483                    None => Ok(0),
484                }
485            }
486        }
487    };
488}
489try_to_unsigned_int!(u128);
490try_to_unsigned_int!(u64);
491try_to_unsigned_int!(u32);
492try_to_unsigned_int!(u16);
493try_to_unsigned_int!(u8);
494try_to_unsigned_int!(usize);
495
496impl From<DynamicDecimal> for f64 {
497    fn from(value: DynamicDecimal) -> Self {
498        match checked_pow10(value.exponent().into()) {
499            Some(divisor) => value.significand() as f64 / divisor as f64,
500            // The divisor does not fit in an `i128`, so parse the decimal digits.
501            None => value.to_string().parse().unwrap(),
502        }
503    }
504}
505
506impl From<DynamicDecimal> for f32 {
507    /// Divides in `f64` and rounds the quotient to `f32`, as the conversion
508    /// from `Fixed` through `f64` does.
509    fn from(value: DynamicDecimal) -> Self {
510        f64::from(value) as f32
511    }
512}
513
514impl TryFrom<f64> for DynamicDecimal {
515    type Error = OutOfRange;
516
517    /// Convert `value` to `DynamicDecimal`, reporting an error if `value` is
518    /// out of range.
519    ///
520    /// This uses the shortest decimal string that round-trips to `value`, the
521    /// same digits as `TryFrom<f64> for Fixed`.
522    fn try_from(value: f64) -> Result<Self, Self::Error> {
523        if !value.is_finite() {
524            return Err(OutOfRange);
525        }
526        ryu::Buffer::new()
527            .format_finite(value)
528            .parse()
529            .map_err(|_| OutOfRange)
530    }
531}
532
533impl PartialOrd for DynamicDecimal {
534    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
535        Some(self.cmp(other))
536    }
537}
538
539impl Ord for DynamicDecimal {
540    fn cmp(&self, other: &Self) -> Ordering {
541        match self.exponent.cmp(&other.exponent) {
542            Ordering::Less => {
543                if let Some(multiplier) =
544                    checked_pow10(other.exponent as u32 - self.exponent as u32)
545                {
546                    I256::from_product(self.sig, multiplier).cmp(&I256::from(other.sig))
547                } else {
548                    match self.sig.cmp(&0) {
549                        Ordering::Equal => 0.cmp(&other.sig),
550                        ordering => ordering,
551                    }
552                }
553            }
554            Ordering::Equal => self.sig.cmp(&other.sig),
555            Ordering::Greater => {
556                if let Some(multiplier) =
557                    checked_pow10(self.exponent as u32 - other.exponent as u32)
558                {
559                    I256::from(self.sig).cmp(&I256::from_product(other.sig, multiplier))
560                } else {
561                    match other.sig.cmp(&0) {
562                        Ordering::Equal => self.sig.cmp(&0),
563                        ordering => ordering.reverse(),
564                    }
565                }
566            }
567        }
568    }
569}
570
571/// Supports uniform sampling for DynamicDecimals with a specified scale.
572// This is almost like UniformSampler, but we need to pass additional information
573// to the constructor, so we cannot use that trait.
574#[derive(Clone, Debug)]
575pub struct UniformDecimal {
576    significand: UniformInt<i128>,
577    scale: u8,
578}
579
580impl UniformDecimal {
581    /// Create a new UniformDecimal which will sample between
582    /// DynamicDecimal::new(low, scale) and DynamicDecimal::new(high, scale).
583    pub fn new(low: i128, high: i128, scale: u8) -> Self {
584        if low >= high {
585            panic!("Invalid range");
586        }
587        Self {
588            significand: UniformInt::new(&low, &high),
589            scale,
590        }
591    }
592
593    /// Sample uniformly for this range
594    pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> DynamicDecimal {
595        let value = self.significand.sample(rng);
596        DynamicDecimal::new(value, self.scale)
597    }
598}
599
600#[cfg(test)]
601mod test {
602    use crate::{DynamicDecimal, OutOfRange, ParseDecimalError};
603    use num_traits::CheckedMul;
604
605    #[test]
606    fn eq() {
607        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(1230, 3));
608        assert_eq!(DynamicDecimal::new(1230, 3), DynamicDecimal::new(123, 2));
609        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 2));
610        assert_ne!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 3));
611    }
612
613    #[test]
614    fn compare() {
615        type DD = DynamicDecimal;
616        fn check_comparisons(dx: DD, dy: DD, x: i128, y: i128) {
617            assert_eq!(dx == dy, x == y);
618            assert_eq!(dx != dy, x != y);
619            assert_eq!(dx > dy, x > y);
620            assert_eq!(dx >= dy, x >= y);
621            assert_eq!(dx < dy, x < y);
622            assert_eq!(dx <= dy, x <= y);
623        }
624
625        for x in -999..=999 {
626            let fx = DD::new(x, 1);
627            for y in -999..=999 {
628                check_comparisons(fx, DD::new(y, 0), x, y * 10);
629                check_comparisons(fx, DD::new(y, 1), x, y);
630                check_comparisons(fx, DD::new(y, 2), x * 10, y);
631            }
632        }
633
634        // Some handwritten overflow cases.
635        check_comparisons(DD::new(0, 40), DD::new(0, 0), 0, 0);
636        check_comparisons(DD::new(0, 0), DD::new(0, 40), 0, 0);
637
638        check_comparisons(DD::new(1, 40), DD::new(1, 0), 0, 1);
639        check_comparisons(DD::new(1, 40), DD::new(-1, 0), 1, 0);
640        check_comparisons(DD::new(-1, 40), DD::new(1, 0), 0, 1);
641        check_comparisons(DD::new(-1, 40), DD::new(-1, 0), 1, 0);
642
643        check_comparisons(DD::new(1, 0), DD::new(1, 40), 1, 0);
644        check_comparisons(DD::new(1, 0), DD::new(-1, 40), 1, 0);
645        check_comparisons(DD::new(-1, 0), DD::new(1, 40), 0, 1);
646        check_comparisons(DD::new(-1, 0), DD::new(-1, 40), 0, 1);
647    }
648
649    #[test]
650    fn from_str() {
651        for (s, expect) in [
652            ("0", Ok("0")),
653            ("0.", Ok("0")),
654            (".0", Ok("0")),
655            ("-0", Ok("0")),
656            ("+0", Ok("0")),
657            ("--0", Err(ParseDecimalError::SyntaxError)),
658            ("-+0", Err(ParseDecimalError::SyntaxError)),
659            ("0x", Err(ParseDecimalError::SyntaxError)),
660            ("0e5x", Err(ParseDecimalError::SyntaxError)),
661            ("1.23", Ok("1.23")),
662            ("-1.23", Ok("-1.23")),
663            ("+1.23", Ok("1.23")),
664            ("99999999", Ok("99999999")),
665            ("999999999", Ok("999999999")),
666            ("999999999E-1", Ok("99999999.9")),
667            ("9999999999e-1", Ok("999999999.9")),
668            ("9999999999E-2", Ok("99999999.99")),
669            ("99999999999e-2", Ok("999999999.99")),
670            ("99999999999e-3", Ok("99999999.999")),
671            ("99999999991e-3", Ok("99999999.991")),
672            // This value overflows the range of `i128` as an integer, so it
673            // triggers the case where we stop accepting digits and simply
674            // adjust the exponent instead.
675            (
676                "111111111111111111111111111111111111111111e-34",
677                Ok("11111111.1111111111111111111111111111111"),
678            ),
679            // This value overflows the range of `i128` in the fraction, so it
680            // triggers the case where we stop accepting digits and simply
681            // adjust the exponent instead.
682            (
683                "1.23456788901234567890123456789012345678890123456",
684                Ok("1.23456788901234567890123456789012345678"),
685            ),
686            // This value positively overflows the exponent.
687            ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
688            // This value positively overflows the exponent but the value is 0.
689            ("0e999999999999999", Ok("0")),
690            // This value negatively overflows the exponent.
691            ("1e-999999999999999", Ok("0")),
692            // This value overflows the range of `i128` as an integer, which
693            // starts adjusting the exponent, and then it overflows the exponent
694            // with `e`.
695            (
696                "111111111111111111111111111111111111111111e2147483644",
697                Err(ParseDecimalError::OutOfRange),
698            ),
699            // This value adjusts the exponent downward, and then it negatively
700            // overflows the exponent with `e`.
701            (
702                ".1111111111111111111111111111111111111111e-2147483648",
703                Ok("0"),
704            ),
705            ("123e5", Ok("12300000")),
706            ("123E4", Ok("1230000")),
707            ("123e3", Ok("123000")),
708            ("123e2", Ok("12300")),
709            ("123e1", Ok("1230")),
710            ("123e0", Ok("123")),
711            ("123e-1", Ok("12.3")),
712            ("123e-2", Ok("1.23")),
713            (".123", Ok("0.123")),
714            (".124", Ok("0.124")),
715            (".125", Ok("0.125")),
716            (".126", Ok("0.126")),
717            (".133", Ok("0.133")),
718            (".134", Ok("0.134")),
719            (".135", Ok("0.135")),
720            (".136", Ok("0.136")),
721            ("1e38", Ok("100000000000000000000000000000000000000")),
722            ("1e39", Err(ParseDecimalError::OutOfRange)),
723            (
724                "1e-255",
725                Ok(
726                    "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
727                ),
728            ),
729            ("1e-256", Ok("0")),
730        ] {
731            println!("{s}: {:?}", s.parse::<DynamicDecimal>());
732            assert_eq!(
733                s.parse::<DynamicDecimal>().map(|d| d.to_string()),
734                expect.map(|d| d.to_string())
735            );
736        }
737    }
738
739    #[test]
740    fn to_integer() {
741        for x in -9999..=9999 {
742            let f = DynamicDecimal::new(x, 1);
743            assert_eq!(i128::from(f), x / 10);
744            assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
745            assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
746            assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
747            assert_eq!(
748                i8::try_from(f).ok(),
749                (-1289..=1279).contains(&x).then_some((x / 10) as i8)
750            );
751            assert_eq!(
752                u128::try_from(f).ok(),
753                (x > -10).then_some((x / 10) as u128)
754            );
755            assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
756            assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
757            assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
758            assert_eq!(
759                u8::try_from(f).ok(),
760                (-9..=2559).contains(&x).then_some((x / 10) as u8)
761            );
762        }
763
764        assert_eq!(i128::from(DynamicDecimal::new(1, 40)), 0);
765        assert_eq!(i128::from(DynamicDecimal::new(i128::MAX, 0)), i128::MAX);
766        assert_eq!(i64::try_from(DynamicDecimal::new(1, 40)), Ok(0));
767        assert_eq!(
768            i64::try_from(DynamicDecimal::new(i128::MAX, 0)),
769            Err(OutOfRange)
770        );
771        assert_eq!(
772            i64::try_from(DynamicDecimal::new(i128::MIN, 0)),
773            Err(OutOfRange)
774        );
775    }
776
777    #[test]
778    fn mul() {
779        fn f(n: f64) -> DynamicDecimal {
780            DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
781        }
782
783        // Same tests as for Fixed
784        // A few specific handwritten cases.
785        assert_eq!((f(1.23) * f(2.34)).trunc_digits(2), f(2.87));
786        assert_eq!((f(-1.23) * f(2.34)).trunc_digits(2), f(-2.87));
787        assert_eq!((f(1.23) * f(-2.34)).trunc_digits(2), f(-2.87));
788        assert_eq!((f(-1.23) * f(-2.34)).trunc_digits(2), f(2.87));
789
790        // General case.
791        for a in -999..=999 {
792            let af: DynamicDecimal = DynamicDecimal::new(a, 2);
793            for b in -999..=999 {
794                let bf = DynamicDecimal::new(b, 2);
795                assert_eq!(af * bf, DynamicDecimal::new(a * b, 4));
796            }
797        }
798    }
799
800    #[test]
801    fn add() {
802        fn f(n: f64) -> DynamicDecimal {
803            DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
804        }
805
806        // A few specific handwritten cases.
807        assert_eq!(f(1.23) + f(2.34), f(3.57));
808        assert_eq!(f(-1.23) + f(2.34), f(1.11));
809        assert_eq!(f(1.23) + f(-2.34), f(-1.11));
810        assert_eq!(f(-1.23) + f(-2.34), f(-3.57));
811
812        for a in -999..=999 {
813            let af = DynamicDecimal::new(a, 2);
814            for b in -999..=999 {
815                let bf = DynamicDecimal::new(b, 2);
816                assert_eq!(af + bf, DynamicDecimal::new(a + b, 2));
817            }
818        }
819    }
820
821    #[test]
822    fn to_f64() {
823        assert_eq!(f64::from(DynamicDecimal::new(15, 1)), 1.5);
824        // 10**100 and 10**44 do not fit in an `i128`.
825        assert_eq!(f64::from(DynamicDecimal::new(1, 100)), 1e-100);
826        assert_eq!(f64::from(DynamicDecimal::new(-12345, 44)), -1.2345e-40);
827    }
828
829    #[test]
830    fn mul_wide() {
831        // The products of these significands do not fit in an `i128`, so `mul`
832        // drops their trailing digits.
833        let x = DynamicDecimal::new(10i128.pow(20) + 1, 10);
834        assert_eq!(x * x, DynamicDecimal::new(10i128.pow(20) + 2, 0));
835        let fraction: DynamicDecimal = "0.12345678901234567890123456789012345".parse().unwrap();
836        let billion = DynamicDecimal::new(1_000_000_000, 0);
837        let expected: DynamicDecimal = "123456789.01234567890123456789012345".parse().unwrap();
838        assert_eq!(fraction * billion, expected);
839        assert_eq!(billion * fraction, expected);
840    }
841
842    #[test]
843    #[should_panic(expected = "Overflow multiplying")]
844    fn mul_overflow() {
845        let x = DynamicDecimal::new(10i128.pow(20), 0);
846        let _ = x * x;
847    }
848
849    #[test]
850    fn checked_mul() {
851        let x = DynamicDecimal::new(10i128.pow(20), 0);
852        assert_eq!(x.checked_mul(&x), None);
853        let y = DynamicDecimal::new(3, 1);
854        assert_eq!(y.checked_mul(&y), Some(DynamicDecimal::new(9, 2)));
855    }
856
857    #[test]
858    fn mul_many_fractional_digits() {
859        // A product with more than 255 fractional digits drops the digits past the 255th.
860        let tiny = DynamicDecimal::new(1, 200);
861        assert_eq!(tiny * tiny, DynamicDecimal::ZERO);
862        let x = DynamicDecimal::new(123456789, 200);
863        let y = DynamicDecimal::new(1, 60);
864        assert_eq!(x * y, DynamicDecimal::new(1234, 255));
865    }
866
867    #[test]
868    fn add_wide() {
869        // `add` computes these sums with 256 bits.
870        let big = DynamicDecimal::new(2 * 10i128.pow(35), 0);
871        let quarter = DynamicDecimal::new(25, 2);
872        let expected: DynamicDecimal = format!("{}.25", 2 * 10i128.pow(35)).parse().unwrap();
873        assert_eq!(big + quarter, expected);
874        assert_eq!(quarter + big, expected);
875        // The digits of 10**37 + 0.001 after the decimal point do not fit.
876        let large = DynamicDecimal::new(10i128.pow(37), 0);
877        let thousandth = DynamicDecimal::new(1, 3);
878        assert_eq!(large + thousandth, large);
879        assert_eq!(thousandth + large, large);
880        // -10**37 * 100 does not fit in an `i128`; -10**37 + 0.25 keeps one fractional digit.
881        let negative: DynamicDecimal = format!("-{}.7", 10i128.pow(37) - 1).parse().unwrap();
882        assert_eq!(-large + quarter, negative);
883        assert_eq!(quarter + -large, negative);
884        // The sum of two significands with the same exponent does not fit in an `i128`.
885        let half_max = DynamicDecimal::new(i128::MAX, 1);
886        assert_eq!(half_max + half_max, DynamicDecimal::new(i128::MAX / 5, 0));
887    }
888
889    #[test]
890    fn add_distant_exponents() {
891        // The exponents differ by more than 38.
892        let one = DynamicDecimal::ONE;
893        let tiny = DynamicDecimal::new(1, 200);
894        assert_eq!(one + tiny, one);
895        assert_eq!(tiny + one, one);
896        assert_eq!(DynamicDecimal::ZERO + tiny, tiny);
897        // 1 - 10**-200 truncates to 37 nines after the decimal point.
898        let nines = DynamicDecimal::new(10i128.pow(37) - 1, 37);
899        assert_eq!(one - tiny, nines);
900        assert_eq!(-one + tiny, -nines);
901        // The leading digits of 1.23 * 10**-37 are kept: 1 + 10**-37 and 1 - 2 * 10**-37.
902        let small = DynamicDecimal::new(123, 39);
903        assert_eq!(one + small, DynamicDecimal::new(10i128.pow(37) + 1, 37));
904        assert_eq!(one - small, DynamicDecimal::new(10i128.pow(37) - 2, 37));
905    }
906
907    #[test]
908    fn sub() {
909        fn f(n: f64) -> DynamicDecimal {
910            DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
911        }
912
913        assert_eq!(f(1.23) - f(2.34), f(-1.11));
914        assert_eq!(f(-1.23) - f(2.34), f(-3.57));
915        assert_eq!(f(1.23) - f(-2.34), f(3.57));
916        assert_eq!(f(-1.23) - f(-2.34), f(1.11));
917
918        for a in -999..=999 {
919            let af = DynamicDecimal::new(a, 2);
920            for b in -999..=999 {
921                let bf = DynamicDecimal::new(b, 2);
922                assert_eq!(af - bf, DynamicDecimal::new(a - b, 2));
923            }
924        }
925    }
926
927    #[test]
928    fn div() {
929        fn f(n: f64) -> DynamicDecimal {
930            DynamicDecimal::try_from(n).unwrap().trunc_digits(6)
931        }
932
933        assert_eq!(f(1.23) / f(2.34), f(0.525641));
934        assert_eq!(f(-1.23) / f(2.34), f(-0.525641));
935        assert_eq!(f(1.23) / f(-2.34), f(-0.525641));
936        assert_eq!(f(-1.23) / f(-2.34), f(0.525641));
937
938        for a in -999..=999 {
939            let af = DynamicDecimal::new(a, 2);
940            for b in -999..=999 {
941                let bf = DynamicDecimal::new(b, 2);
942                if b != 0 {
943                    let expected = DynamicDecimal::new(a * 1000000 / b, 6);
944                    assert_eq!(af / bf, expected);
945                }
946            }
947        }
948    }
949}