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#[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 sig: i128,
58
59 exponent: u8,
61}
62
63impl DynamicDecimal {
64 pub const MAX: Self = DynamicDecimal::new(i128::MAX, 0);
66
67 pub const MIN: Self = DynamicDecimal::new(i128::MIN, 0);
69
70 pub const ZERO: Self = DynamicDecimal::new(0, 0);
72
73 pub const ONE: Self = DynamicDecimal::new(1, 0);
75
76 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 const fn reduce<const D: u8>(mut sig: i128, mut exponent: u8) -> (i128, u8) {
86 let scale = pow10(D as usize);
88
89 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 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 pub const fn significand(&self) -> i128 {
116 self.sig
117 }
118
119 pub const fn exponent(&self) -> u8 {
121 self.exponent
122 }
123
124 pub fn trunc(&self) -> Self {
126 DynamicDecimal::new(self.sig / pow10(self.exponent as usize), 0)
127 }
128
129 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 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 pub const fn is_negative(self) -> bool {
158 self.sig.is_negative()
159 }
160
161 pub const fn abs(self) -> Self {
163 Self::new(self.sig.abs(), self.exponent)
164 }
165
166 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 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 fn add_distant_exponents(coarse: Self, fine: Self) -> Option<Self> {
188 if coarse.sig == 0 {
189 return Some(fine);
190 }
191 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 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 #[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 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 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 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 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 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 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 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 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 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 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
468macro_rules! try_to_unsigned_int {
471 ($type_name:ty) => {
472 impl TryFrom<DynamicDecimal> for $type_name {
473 type Error = OutOfRange;
474
475 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 None => value.to_string().parse().unwrap(),
502 }
503 }
504}
505
506impl From<DynamicDecimal> for f32 {
507 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 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#[derive(Clone, Debug)]
575pub struct UniformDecimal {
576 significand: UniformInt<i128>,
577 scale: u8,
578}
579
580impl UniformDecimal {
581 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 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 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 (
676 "111111111111111111111111111111111111111111e-34",
677 Ok("11111111.1111111111111111111111111111111"),
678 ),
679 (
683 "1.23456788901234567890123456789012345678890123456",
684 Ok("1.23456788901234567890123456789012345678"),
685 ),
686 ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
688 ("0e999999999999999", Ok("0")),
690 ("1e-999999999999999", Ok("0")),
692 (
696 "111111111111111111111111111111111111111111e2147483644",
697 Err(ParseDecimalError::OutOfRange),
698 ),
699 (
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 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 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 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 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 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 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 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 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 let negative: DynamicDecimal = format!("-{}.7", 10i128.pow(37) - 1).parse().unwrap();
882 assert_eq!(-large + quarter, negative);
883 assert_eq!(quarter + -large, negative);
884 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 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 let nines = DynamicDecimal::new(10i128.pow(37) - 1, 37);
899 assert_eq!(one - tiny, nines);
900 assert_eq!(-one + tiny, -nines);
901 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}