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;
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    /// Deserializes [DynamicDecimal] into `Fixed`.  If successful, returns the
167    /// original value from before serialization.  If `S < value.exponent`, then
168    /// some trailing decimals are lost, by rounding toward even.  Returns an
169    /// error` if the value is out of range for this type.
170    #[doc(hidden)]
171    pub fn into_fixed_round_even<const P: usize, const S: usize>(
172        self,
173    ) -> Result<Fixed<P, S>, OutOfRange> {
174        Fixed::<P, S>::try_new_with_exponent_round_even(self.sig, S as i32 - self.exponent as i32)
175            .ok_or(OutOfRange)
176    }
177}
178
179impl<const P: usize, const S: usize> From<Fixed<P, S>> for DynamicDecimal {
180    /// Encodes `value`, for later deserialization into a new `Fixed` with
181    /// possibly a different precision and scale.
182    fn from(value: Fixed<P, S>) -> Self {
183        Self::new(value.0, S as u8)
184    }
185}
186
187impl Neg for DynamicDecimal {
188    type Output = Self;
189
190    fn neg(self) -> Self {
191        DynamicDecimal::new(-self.sig, self.exponent)
192    }
193}
194
195impl Add<DynamicDecimal> for DynamicDecimal {
196    type Output = Self;
197
198    fn add(self, other: Self) -> Self {
199        match self.exponent.cmp(&other.exponent) {
200            Ordering::Less => {
201                let factor = pow10((other.exponent - self.exponent) as usize);
202                if self.sig <= i128::MAX / factor / 10 {
203                    DynamicDecimal::new(
204                        other.sig.checked_add(self.sig * factor).unwrap(),
205                        other.exponent,
206                    )
207                } else {
208                    let result = (I256::from_product(self.sig, factor) + I256::from(other.sig))
209                        .reduce_to_i128();
210                    DynamicDecimal::new(result.0, result.1 as u8)
211                }
212            }
213            Ordering::Equal => {
214                DynamicDecimal::new(self.sig.checked_add(other.sig).unwrap(), self.exponent)
215            }
216            Ordering::Greater => {
217                let factor = pow10((self.exponent - other.exponent) as usize);
218                if other.sig <= i128::MAX / factor / 10 {
219                    DynamicDecimal::new(
220                        self.sig.checked_add(other.sig * factor).unwrap(),
221                        self.exponent,
222                    )
223                } else {
224                    let result = (I256::from_product(other.sig, factor) + I256::from(self.sig))
225                        .reduce_to_i128();
226                    DynamicDecimal::new(result.0, result.1 as u8)
227                }
228            }
229        }
230    }
231}
232
233impl Sub<DynamicDecimal> for DynamicDecimal {
234    type Output = Self;
235
236    fn sub(self, other: Self) -> Self {
237        self.add(other.neg())
238    }
239}
240
241impl Mul<DynamicDecimal> for DynamicDecimal {
242    type Output = Self;
243
244    fn mul(self, other: Self) -> Self {
245        let result = I256::from_product(self.sig, other.sig).reduce_to_i128();
246        DynamicDecimal::new(result.0, result.1 as u8 + self.exponent + other.exponent)
247    }
248}
249
250impl CheckedDiv for DynamicDecimal {
251    fn checked_div(&self, other: &DynamicDecimal) -> Option<DynamicDecimal> {
252        if other.sig == 0i128 {
253            None
254        } else {
255            // We have to choose an arbitrary number of digits after the decimal
256            // point where we stop.
257            const MIN_DIGITS: u8 = 6;
258            let digits = std::cmp::max(std::cmp::max(MIN_DIGITS, self.exponent), other.exponent);
259
260            let shift_left = (other.exponent + digits).saturating_sub(self.exponent);
261            if shift_left > 38 {
262                // A shift this big would exceed the range of I256, so we can't
263                // calculate it, but the ultimate result would also overflow, so
264                // we don't have to.
265                None
266            } else {
267                let scaled = I256::from_product(self.sig, pow10(shift_left as usize));
268                let div = scaled.narrowing_div(other.sig).unwrap();
269                let exp = self.exponent.saturating_sub(other.exponent + digits);
270                let adjust = div * pow10(exp as usize);
271                Some(DynamicDecimal::new(adjust, digits))
272            }
273        }
274    }
275}
276
277impl Div<DynamicDecimal> for DynamicDecimal {
278    type Output = Self;
279
280    fn div(self, other: DynamicDecimal) -> DynamicDecimal {
281        match self.checked_div(&other) {
282            None => panic!("Overflow dividing {} / {}", self, other),
283            Some(v) => v,
284        }
285    }
286}
287
288impl Rem<DynamicDecimal> for DynamicDecimal {
289    type Output = Self;
290
291    fn rem(self, other: Self) -> Self {
292        let neg = self.is_negative();
293        let left = self.abs();
294        let right = other.abs();
295        let div = left.div(right);
296        let trunc = div.trunc();
297        let mul = right.mul(trunc);
298        let rem = left.sub(mul);
299        if neg { rem.neg() } else { rem }
300    }
301}
302
303impl<const P: usize, const S: usize> TryFrom<DynamicDecimal> for Fixed<P, S> {
304    type Error = OutOfRange;
305
306    /// Deserializes [DynamicDecimal] into `Fixed`.  If successful, returns the
307    /// original value from before serialization.  If `S < value.exponent`, then
308    /// some trailing decimals are lost, by rounding toward zero.  Returns an
309    /// error` if the value is out of range for this type.
310    fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
311        Self::try_new_with_exponent(value.sig, S as i32 - value.exponent as i32).ok_or(OutOfRange)
312    }
313}
314
315impl Debug for DynamicDecimal {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        debug_decimal(self.sig, self.exponent as usize, f)
318    }
319}
320
321impl Display for DynamicDecimal {
322    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323        display_decimal(self.sig, self.exponent as usize, f)
324    }
325}
326
327impl FromStr for DynamicDecimal {
328    type Err = ParseDecimalError;
329
330    /// Parses `s` as `DynamicDecimal`.
331    ///
332    /// This accepts the same forms as [f64::from_str], except that it rejects
333    /// infinities and NaNs (which `Fixed` does not support), as well as
334    /// out-of-range values.  Rounds overprecise values to the nearest
335    /// representable value, rounding halfway values to even.
336    fn from_str(s: &str) -> Result<Self, Self::Err> {
337        let (sig, exponent) = parse_decimal(s, 0)?;
338        match (sig, exponent) {
339            (0, _) => Ok(Self::ZERO),
340            (_, 1..) => {
341                let sig = checked_pow10(exponent.cast_unsigned())
342                    .and_then(|m| m.checked_mul(sig))
343                    .ok_or(ParseDecimalError::OutOfRange)?;
344                Ok(Self::new(sig, 0))
345            }
346            (_, 0) => Ok(Self { sig, exponent: 0 }),
347            (_, -255..0) => Ok(Self::new(sig, (-exponent) as u8)),
348            (_, ..-255) => {
349                // We could "denormalize" by dividing `sig` by a power of 10 and
350                // adjusting `exponent`, but the value would inevitably be zero
351                // when we convert to `Fixed`, which is what we really care
352                // about.
353                Ok(Self::ZERO)
354            }
355        }
356    }
357}
358
359impl TryFrom<u128> for DynamicDecimal {
360    type Error = OutOfRange;
361
362    fn try_from(value: u128) -> Result<Self, Self::Error> {
363        Ok(Self::new(value.try_into().map_err(|_| OutOfRange)?, 0))
364    }
365}
366
367macro_rules! from_int {
368    ($type_name:ty) => {
369        impl From<$type_name> for DynamicDecimal {
370            fn from(value: $type_name) -> Self {
371                Self::new(value as i128, 0)
372            }
373        }
374    };
375}
376from_int!(i128);
377from_int!(i64);
378from_int!(i32);
379from_int!(i16);
380from_int!(i8);
381from_int!(isize);
382from_int!(u64);
383from_int!(u32);
384from_int!(u16);
385from_int!(u8);
386from_int!(usize);
387
388impl From<DynamicDecimal> for i128 {
389    /// Convert from `Fixed` to integer, rounding toward zero (the same
390    /// semantics as Rust casts from float to integer).
391    fn from(value: DynamicDecimal) -> Self {
392        checked_pow10(value.exponent.into()).map_or(0, |divisor| value.sig / divisor)
393    }
394}
395
396macro_rules! try_to_signed_int {
397    ($type_name:ty) => {
398        impl TryFrom<DynamicDecimal> for $type_name {
399            type Error = OutOfRange;
400
401            /// Convert from `Fixed` to integer, rounding toward zero (the same
402            /// semantics as Rust casts from float to integer).
403            fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
404                match checked_pow10(value.exponent.into()) {
405                    Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
406                    None => Ok(0),
407                }
408            }
409        }
410    };
411}
412try_to_signed_int!(i64);
413try_to_signed_int!(i32);
414try_to_signed_int!(i16);
415try_to_signed_int!(i8);
416try_to_signed_int!(isize);
417
418/// This is the same as [try_to_signed_int] except for the documentation
419/// comment.
420macro_rules! try_to_unsigned_int {
421    ($type_name:ty) => {
422        impl TryFrom<DynamicDecimal> for $type_name {
423            type Error = OutOfRange;
424
425            /// Convert from `Fixed` to integer, rounding toward zero (the same
426            /// semantics as Rust casts from float to integer).
427            ///
428            /// Because this rounds toward zero, negative values greater than -1
429            /// will convert to 0 instead of an out-of-range error.
430            fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
431                match checked_pow10(value.exponent.into()) {
432                    Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
433                    None => Ok(0),
434                }
435            }
436        }
437    };
438}
439try_to_unsigned_int!(u128);
440try_to_unsigned_int!(u64);
441try_to_unsigned_int!(u32);
442try_to_unsigned_int!(u16);
443try_to_unsigned_int!(u8);
444try_to_unsigned_int!(usize);
445
446impl From<DynamicDecimal> for f64 {
447    fn from(value: DynamicDecimal) -> Self {
448        value.significand() as f64 / pow10(value.exponent() as usize) as f64
449    }
450}
451
452impl From<DynamicDecimal> for f32 {
453    /// Divides in `f64` and rounds the quotient to `f32`, as the conversion
454    /// from `Fixed` through `f64` does.
455    fn from(value: DynamicDecimal) -> Self {
456        f64::from(value) as f32
457    }
458}
459
460impl TryFrom<f64> for DynamicDecimal {
461    type Error = OutOfRange;
462
463    /// Convert `value` to `DynamicDecimal`, reporting an error if `value` is
464    /// out of range.
465    ///
466    /// This uses the shortest decimal string that round-trips to `value`, the
467    /// same digits as `TryFrom<f64> for Fixed`.
468    fn try_from(value: f64) -> Result<Self, Self::Error> {
469        if !value.is_finite() {
470            return Err(OutOfRange);
471        }
472        ryu::Buffer::new()
473            .format_finite(value)
474            .parse()
475            .map_err(|_| OutOfRange)
476    }
477}
478
479impl PartialOrd for DynamicDecimal {
480    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
481        Some(self.cmp(other))
482    }
483}
484
485impl Ord for DynamicDecimal {
486    fn cmp(&self, other: &Self) -> Ordering {
487        match self.exponent.cmp(&other.exponent) {
488            Ordering::Less => {
489                if let Some(multiplier) =
490                    checked_pow10(other.exponent as u32 - self.exponent as u32)
491                {
492                    I256::from_product(self.sig, multiplier).cmp(&I256::from(other.sig))
493                } else {
494                    match self.sig.cmp(&0) {
495                        Ordering::Equal => 0.cmp(&other.sig),
496                        ordering => ordering,
497                    }
498                }
499            }
500            Ordering::Equal => self.sig.cmp(&other.sig),
501            Ordering::Greater => {
502                if let Some(multiplier) =
503                    checked_pow10(self.exponent as u32 - other.exponent as u32)
504                {
505                    I256::from(self.sig).cmp(&I256::from_product(other.sig, multiplier))
506                } else {
507                    match other.sig.cmp(&0) {
508                        Ordering::Equal => self.sig.cmp(&0),
509                        ordering => ordering.reverse(),
510                    }
511                }
512            }
513        }
514    }
515}
516
517/// Supports uniform sampling for DynamicDecimals with a specified scale.
518// This is almost like UniformSampler, but we need to pass additional information
519// to the constructor, so we cannot use that trait.
520#[derive(Clone, Debug)]
521pub struct UniformDecimal {
522    significand: UniformInt<i128>,
523    scale: u8,
524}
525
526impl UniformDecimal {
527    /// Create a new UniformDecimal which will sample between
528    /// DynamicDecimal::new(low, scale) and DynamicDecimal::new(high, scale).
529    pub fn new(low: i128, high: i128, scale: u8) -> Self {
530        if low >= high {
531            panic!("Invalid range");
532        }
533        Self {
534            significand: UniformInt::new(&low, &high),
535            scale,
536        }
537    }
538
539    /// Sample uniformly for this range
540    pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> DynamicDecimal {
541        let value = self.significand.sample(rng);
542        DynamicDecimal::new(value, self.scale)
543    }
544}
545
546#[cfg(test)]
547mod test {
548    use crate::{DynamicDecimal, OutOfRange, ParseDecimalError};
549
550    #[test]
551    fn eq() {
552        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(1230, 3));
553        assert_eq!(DynamicDecimal::new(1230, 3), DynamicDecimal::new(123, 2));
554        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 2));
555        assert_ne!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 3));
556    }
557
558    #[test]
559    fn compare() {
560        type DD = DynamicDecimal;
561        fn check_comparisons(dx: DD, dy: DD, x: i128, y: i128) {
562            assert_eq!(dx == dy, x == y);
563            assert_eq!(dx != dy, x != y);
564            assert_eq!(dx > dy, x > y);
565            assert_eq!(dx >= dy, x >= y);
566            assert_eq!(dx < dy, x < y);
567            assert_eq!(dx <= dy, x <= y);
568        }
569
570        for x in -999..=999 {
571            let fx = DD::new(x, 1);
572            for y in -999..=999 {
573                check_comparisons(fx, DD::new(y, 0), x, y * 10);
574                check_comparisons(fx, DD::new(y, 1), x, y);
575                check_comparisons(fx, DD::new(y, 2), x * 10, y);
576            }
577        }
578
579        // Some handwritten overflow cases.
580        check_comparisons(DD::new(0, 40), DD::new(0, 0), 0, 0);
581        check_comparisons(DD::new(0, 0), DD::new(0, 40), 0, 0);
582
583        check_comparisons(DD::new(1, 40), DD::new(1, 0), 0, 1);
584        check_comparisons(DD::new(1, 40), DD::new(-1, 0), 1, 0);
585        check_comparisons(DD::new(-1, 40), DD::new(1, 0), 0, 1);
586        check_comparisons(DD::new(-1, 40), DD::new(-1, 0), 1, 0);
587
588        check_comparisons(DD::new(1, 0), DD::new(1, 40), 1, 0);
589        check_comparisons(DD::new(1, 0), DD::new(-1, 40), 1, 0);
590        check_comparisons(DD::new(-1, 0), DD::new(1, 40), 0, 1);
591        check_comparisons(DD::new(-1, 0), DD::new(-1, 40), 0, 1);
592    }
593
594    #[test]
595    fn from_str() {
596        for (s, expect) in [
597            ("0", Ok("0")),
598            ("0.", Ok("0")),
599            (".0", Ok("0")),
600            ("-0", Ok("0")),
601            ("+0", Ok("0")),
602            ("--0", Err(ParseDecimalError::SyntaxError)),
603            ("-+0", Err(ParseDecimalError::SyntaxError)),
604            ("0x", Err(ParseDecimalError::SyntaxError)),
605            ("0e5x", Err(ParseDecimalError::SyntaxError)),
606            ("1.23", Ok("1.23")),
607            ("-1.23", Ok("-1.23")),
608            ("+1.23", Ok("1.23")),
609            ("99999999", Ok("99999999")),
610            ("999999999", Ok("999999999")),
611            ("999999999E-1", Ok("99999999.9")),
612            ("9999999999e-1", Ok("999999999.9")),
613            ("9999999999E-2", Ok("99999999.99")),
614            ("99999999999e-2", Ok("999999999.99")),
615            ("99999999999e-3", Ok("99999999.999")),
616            ("99999999991e-3", Ok("99999999.991")),
617            // This value overflows the range of `i128` as an integer, so it
618            // triggers the case where we stop accepting digits and simply
619            // adjust the exponent instead.
620            (
621                "111111111111111111111111111111111111111111e-34",
622                Ok("11111111.1111111111111111111111111111111"),
623            ),
624            // This value overflows the range of `i128` in the fraction, so it
625            // triggers the case where we stop accepting digits and simply
626            // adjust the exponent instead.
627            (
628                "1.23456788901234567890123456789012345678890123456",
629                Ok("1.23456788901234567890123456789012345678"),
630            ),
631            // This value positively overflows the exponent.
632            ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
633            // This value positively overflows the exponent but the value is 0.
634            ("0e999999999999999", Ok("0")),
635            // This value negatively overflows the exponent.
636            ("1e-999999999999999", Ok("0")),
637            // This value overflows the range of `i128` as an integer, which
638            // starts adjusting the exponent, and then it overflows the exponent
639            // with `e`.
640            (
641                "111111111111111111111111111111111111111111e2147483644",
642                Err(ParseDecimalError::OutOfRange),
643            ),
644            // This value adjusts the exponent downward, and then it negatively
645            // overflows the exponent with `e`.
646            (
647                ".1111111111111111111111111111111111111111e-2147483648",
648                Ok("0"),
649            ),
650            ("123e5", Ok("12300000")),
651            ("123E4", Ok("1230000")),
652            ("123e3", Ok("123000")),
653            ("123e2", Ok("12300")),
654            ("123e1", Ok("1230")),
655            ("123e0", Ok("123")),
656            ("123e-1", Ok("12.3")),
657            ("123e-2", Ok("1.23")),
658            (".123", Ok("0.123")),
659            (".124", Ok("0.124")),
660            (".125", Ok("0.125")),
661            (".126", Ok("0.126")),
662            (".133", Ok("0.133")),
663            (".134", Ok("0.134")),
664            (".135", Ok("0.135")),
665            (".136", Ok("0.136")),
666            ("1e38", Ok("100000000000000000000000000000000000000")),
667            ("1e39", Err(ParseDecimalError::OutOfRange)),
668            (
669                "1e-255",
670                Ok(
671                    "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
672                ),
673            ),
674            ("1e-256", Ok("0")),
675        ] {
676            println!("{s}: {:?}", s.parse::<DynamicDecimal>());
677            assert_eq!(
678                s.parse::<DynamicDecimal>().map(|d| d.to_string()),
679                expect.map(|d| d.to_string())
680            );
681        }
682    }
683
684    #[test]
685    fn to_integer() {
686        for x in -9999..=9999 {
687            let f = DynamicDecimal::new(x, 1);
688            assert_eq!(i128::from(f), x / 10);
689            assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
690            assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
691            assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
692            assert_eq!(
693                i8::try_from(f).ok(),
694                (-1289..=1279).contains(&x).then_some((x / 10) as i8)
695            );
696            assert_eq!(
697                u128::try_from(f).ok(),
698                (x > -10).then_some((x / 10) as u128)
699            );
700            assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
701            assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
702            assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
703            assert_eq!(
704                u8::try_from(f).ok(),
705                (-9..=2559).contains(&x).then_some((x / 10) as u8)
706            );
707        }
708
709        assert_eq!(i128::from(DynamicDecimal::new(1, 40)), 0);
710        assert_eq!(i128::from(DynamicDecimal::new(i128::MAX, 0)), i128::MAX);
711        assert_eq!(i64::try_from(DynamicDecimal::new(1, 40)), Ok(0));
712        assert_eq!(
713            i64::try_from(DynamicDecimal::new(i128::MAX, 0)),
714            Err(OutOfRange)
715        );
716        assert_eq!(
717            i64::try_from(DynamicDecimal::new(i128::MIN, 0)),
718            Err(OutOfRange)
719        );
720    }
721
722    #[test]
723    fn mul() {
724        fn f(n: f64) -> DynamicDecimal {
725            DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
726        }
727
728        // Same tests as for Fixed
729        // A few specific handwritten cases.
730        assert_eq!((f(1.23) * f(2.34)).trunc_digits(2), f(2.87));
731        assert_eq!((f(-1.23) * f(2.34)).trunc_digits(2), f(-2.87));
732        assert_eq!((f(1.23) * f(-2.34)).trunc_digits(2), f(-2.87));
733        assert_eq!((f(-1.23) * f(-2.34)).trunc_digits(2), f(2.87));
734
735        // General case.
736        for a in -999..=999 {
737            let af: DynamicDecimal = DynamicDecimal::new(a, 2);
738            for b in -999..=999 {
739                let bf = DynamicDecimal::new(b, 2);
740                assert_eq!(af * bf, DynamicDecimal::new(a * b, 4));
741            }
742        }
743    }
744
745    #[test]
746    fn add() {
747        fn f(n: f64) -> DynamicDecimal {
748            DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
749        }
750
751        // A few specific handwritten cases.
752        assert_eq!(f(1.23) + f(2.34), f(3.57));
753        assert_eq!(f(-1.23) + f(2.34), f(1.11));
754        assert_eq!(f(1.23) + f(-2.34), f(-1.11));
755        assert_eq!(f(-1.23) + f(-2.34), f(-3.57));
756
757        for a in -999..=999 {
758            let af = DynamicDecimal::new(a, 2);
759            for b in -999..=999 {
760                let bf = DynamicDecimal::new(b, 2);
761                assert_eq!(af + bf, DynamicDecimal::new(a + b, 2));
762            }
763        }
764    }
765
766    #[test]
767    fn sub() {
768        fn f(n: f64) -> DynamicDecimal {
769            DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
770        }
771
772        assert_eq!(f(1.23) - f(2.34), f(-1.11));
773        assert_eq!(f(-1.23) - f(2.34), f(-3.57));
774        assert_eq!(f(1.23) - f(-2.34), f(3.57));
775        assert_eq!(f(-1.23) - f(-2.34), f(1.11));
776
777        for a in -999..=999 {
778            let af = DynamicDecimal::new(a, 2);
779            for b in -999..=999 {
780                let bf = DynamicDecimal::new(b, 2);
781                assert_eq!(af - bf, DynamicDecimal::new(a - b, 2));
782            }
783        }
784    }
785
786    #[test]
787    fn div() {
788        fn f(n: f64) -> DynamicDecimal {
789            DynamicDecimal::try_from(n).unwrap().trunc_digits(6)
790        }
791
792        assert_eq!(f(1.23) / f(2.34), f(0.525641));
793        assert_eq!(f(-1.23) / f(2.34), f(-0.525641));
794        assert_eq!(f(1.23) / f(-2.34), f(-0.525641));
795        assert_eq!(f(-1.23) / f(-2.34), f(0.525641));
796
797        for a in -999..=999 {
798            let af = DynamicDecimal::new(a, 2);
799            for b in -999..=999 {
800                let bf = DynamicDecimal::new(b, 2);
801                if b != 0 {
802                    let expected = DynamicDecimal::new(a * 1000000 / b, 6);
803                    assert_eq!(af / bf, expected);
804                }
805            }
806        }
807    }
808}