feldera_fxp/
dynamic.rs

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