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 Fixed, OutOfRange, ParseDecimalError, checked_pow10, debug_decimal, display_decimal,
12 parse_decimal, pow10, u256::I256,
13};
14
15use rand::Rng;
16use rand::distributions::uniform::{UniformInt, UniformSampler};
17
18#[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 sig: i128,
59
60 exponent: u8,
62}
63
64impl DynamicDecimal {
65 pub const MAX: Self = DynamicDecimal::new(i128::MAX, 0);
67
68 pub const MIN: Self = DynamicDecimal::new(i128::MIN, 0);
70
71 pub const ZERO: Self = DynamicDecimal::new(0, 0);
73
74 pub const ONE: Self = DynamicDecimal::new(1, 0);
76
77 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 const fn reduce<const D: u8>(mut sig: i128, mut exponent: u8) -> (i128, u8) {
87 let scale = pow10(D as usize);
89
90 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 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 pub const fn significand(&self) -> i128 {
117 self.sig
118 }
119
120 pub const fn exponent(&self) -> u8 {
122 self.exponent
123 }
124
125 pub fn trunc(&self) -> Self {
127 DynamicDecimal::new(self.sig / pow10(self.exponent as usize), 0)
128 }
129
130 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 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 pub const fn is_negative(self) -> bool {
159 self.sig.is_negative()
160 }
161
162 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 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 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 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 { rem.neg() } else { rem }
280 }
281}
282
283impl<const P: usize, const S: usize> TryFrom<DynamicDecimal> for Fixed<P, S> {
284 type Error = OutOfRange;
285
286 fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
291 Self::try_new_with_exponent(value.sig, S as i32 - value.exponent as i32).ok_or(OutOfRange)
292 }
293}
294
295impl Debug for DynamicDecimal {
296 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 debug_decimal(self.sig, self.exponent as usize, f)
298 }
299}
300
301impl Display for DynamicDecimal {
302 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
303 display_decimal(self.sig, self.exponent as usize, f)
304 }
305}
306
307impl FromStr for DynamicDecimal {
308 type Err = ParseDecimalError;
309
310 fn from_str(s: &str) -> Result<Self, Self::Err> {
317 let (sig, exponent) = parse_decimal(s, 0)?;
318 match (sig, exponent) {
319 (0, _) => Ok(Self::ZERO),
320 (_, 1..) => {
321 let sig = checked_pow10(exponent.cast_unsigned())
322 .and_then(|m| m.checked_mul(sig))
323 .ok_or(ParseDecimalError::OutOfRange)?;
324 Ok(Self::new(sig, 0))
325 }
326 (_, 0) => Ok(Self { sig, exponent: 0 }),
327 (_, -255..0) => Ok(Self::new(sig, (-exponent) as u8)),
328 (_, ..-255) => {
329 Ok(Self::ZERO)
334 }
335 }
336 }
337}
338
339impl TryFrom<u128> for DynamicDecimal {
340 type Error = OutOfRange;
341
342 fn try_from(value: u128) -> Result<Self, Self::Error> {
343 Ok(Self::new(value.try_into().map_err(|_| OutOfRange)?, 0))
344 }
345}
346
347macro_rules! from_int {
348 ($type_name:ty) => {
349 impl From<$type_name> for DynamicDecimal {
350 fn from(value: $type_name) -> Self {
351 Self::new(value as i128, 0)
352 }
353 }
354 };
355}
356from_int!(i128);
357from_int!(i64);
358from_int!(i32);
359from_int!(i16);
360from_int!(i8);
361from_int!(isize);
362from_int!(u64);
363from_int!(u32);
364from_int!(u16);
365from_int!(u8);
366from_int!(usize);
367
368impl From<DynamicDecimal> for i128 {
369 fn from(value: DynamicDecimal) -> Self {
372 checked_pow10(value.exponent.into()).map_or(0, |divisor| value.sig / divisor)
373 }
374}
375
376macro_rules! try_to_signed_int {
377 ($type_name:ty) => {
378 impl TryFrom<DynamicDecimal> for $type_name {
379 type Error = OutOfRange;
380
381 fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
384 match checked_pow10(value.exponent.into()) {
385 Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
386 None => Ok(0),
387 }
388 }
389 }
390 };
391}
392try_to_signed_int!(i64);
393try_to_signed_int!(i32);
394try_to_signed_int!(i16);
395try_to_signed_int!(i8);
396try_to_signed_int!(isize);
397
398macro_rules! try_to_unsigned_int {
401 ($type_name:ty) => {
402 impl TryFrom<DynamicDecimal> for $type_name {
403 type Error = OutOfRange;
404
405 fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
411 match checked_pow10(value.exponent.into()) {
412 Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
413 None => Ok(0),
414 }
415 }
416 }
417 };
418}
419try_to_unsigned_int!(u128);
420try_to_unsigned_int!(u64);
421try_to_unsigned_int!(u32);
422try_to_unsigned_int!(u16);
423try_to_unsigned_int!(u8);
424try_to_unsigned_int!(usize);
425
426impl From<DynamicDecimal> for f64 {
427 fn from(value: DynamicDecimal) -> Self {
428 value.significand() as f64 / pow10(value.exponent() as usize) as f64
429 }
430}
431
432impl From<DynamicDecimal> for f32 {
433 fn from(value: DynamicDecimal) -> Self {
434 value.significand() as f32 / pow10(value.exponent() as usize) as f32
435 }
436}
437
438impl TryFrom<f64> for DynamicDecimal {
439 type Error = OutOfRange;
440
441 fn try_from(value: f64) -> Result<Self, Self::Error> {
444 let mut buf = SmallString::<[u8; 64]>::new();
450 write!(&mut buf, "{value:.15e}").unwrap();
451 buf.parse().map_err(|_| OutOfRange)
452 }
453}
454
455impl PartialOrd for DynamicDecimal {
456 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
457 Some(self.cmp(other))
458 }
459}
460
461impl Ord for DynamicDecimal {
462 fn cmp(&self, other: &Self) -> Ordering {
463 match self.exponent.cmp(&other.exponent) {
464 Ordering::Less => {
465 if let Some(multiplier) =
466 checked_pow10(other.exponent as u32 - self.exponent as u32)
467 {
468 I256::from_product(self.sig, multiplier).cmp(&I256::from(other.sig))
469 } else {
470 match self.sig.cmp(&0) {
471 Ordering::Equal => 0.cmp(&other.sig),
472 ordering => ordering,
473 }
474 }
475 }
476 Ordering::Equal => self.sig.cmp(&other.sig),
477 Ordering::Greater => {
478 if let Some(multiplier) =
479 checked_pow10(self.exponent as u32 - other.exponent as u32)
480 {
481 I256::from(self.sig).cmp(&I256::from_product(other.sig, multiplier))
482 } else {
483 match other.sig.cmp(&0) {
484 Ordering::Equal => self.sig.cmp(&0),
485 ordering => ordering.reverse(),
486 }
487 }
488 }
489 }
490 }
491}
492
493#[derive(Clone, Debug)]
497pub struct UniformDecimal {
498 significand: UniformInt<i128>,
499 scale: u8,
500}
501
502impl UniformDecimal {
503 pub fn new(low: i128, high: i128, scale: u8) -> Self {
506 if low >= high {
507 panic!("Invalid range");
508 }
509 Self {
510 significand: UniformInt::new(&low, &high),
511 scale,
512 }
513 }
514
515 pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> DynamicDecimal {
517 let value = self.significand.sample(rng);
518 DynamicDecimal::new(value, self.scale)
519 }
520}
521
522#[cfg(test)]
523mod test {
524 use crate::{DynamicDecimal, OutOfRange, ParseDecimalError};
525
526 #[test]
527 fn eq() {
528 assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(1230, 3));
529 assert_eq!(DynamicDecimal::new(1230, 3), DynamicDecimal::new(123, 2));
530 assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 2));
531 assert_ne!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 3));
532 }
533
534 #[test]
535 fn compare() {
536 type DD = DynamicDecimal;
537 fn check_comparisons(dx: DD, dy: DD, x: i128, y: i128) {
538 assert_eq!(dx == dy, x == y);
539 assert_eq!(dx != dy, x != y);
540 assert_eq!(dx > dy, x > y);
541 assert_eq!(dx >= dy, x >= y);
542 assert_eq!(dx < dy, x < y);
543 assert_eq!(dx <= dy, x <= y);
544 }
545
546 for x in -999..=999 {
547 let fx = DD::new(x, 1);
548 for y in -999..=999 {
549 check_comparisons(fx, DD::new(y, 0), x, y * 10);
550 check_comparisons(fx, DD::new(y, 1), x, y);
551 check_comparisons(fx, DD::new(y, 2), x * 10, y);
552 }
553 }
554
555 check_comparisons(DD::new(0, 40), DD::new(0, 0), 0, 0);
557 check_comparisons(DD::new(0, 0), DD::new(0, 40), 0, 0);
558
559 check_comparisons(DD::new(1, 40), DD::new(1, 0), 0, 1);
560 check_comparisons(DD::new(1, 40), DD::new(-1, 0), 1, 0);
561 check_comparisons(DD::new(-1, 40), DD::new(1, 0), 0, 1);
562 check_comparisons(DD::new(-1, 40), DD::new(-1, 0), 1, 0);
563
564 check_comparisons(DD::new(1, 0), DD::new(1, 40), 1, 0);
565 check_comparisons(DD::new(1, 0), DD::new(-1, 40), 1, 0);
566 check_comparisons(DD::new(-1, 0), DD::new(1, 40), 0, 1);
567 check_comparisons(DD::new(-1, 0), DD::new(-1, 40), 0, 1);
568 }
569
570 #[test]
571 fn from_str() {
572 for (s, expect) in [
573 ("0", Ok("0")),
574 ("0.", Ok("0")),
575 (".0", Ok("0")),
576 ("-0", Ok("0")),
577 ("+0", Ok("0")),
578 ("--0", Err(ParseDecimalError::SyntaxError)),
579 ("-+0", Err(ParseDecimalError::SyntaxError)),
580 ("0x", Err(ParseDecimalError::SyntaxError)),
581 ("0e5x", Err(ParseDecimalError::SyntaxError)),
582 ("1.23", Ok("1.23")),
583 ("-1.23", Ok("-1.23")),
584 ("+1.23", Ok("1.23")),
585 ("99999999", Ok("99999999")),
586 ("999999999", Ok("999999999")),
587 ("999999999E-1", Ok("99999999.9")),
588 ("9999999999e-1", Ok("999999999.9")),
589 ("9999999999E-2", Ok("99999999.99")),
590 ("99999999999e-2", Ok("999999999.99")),
591 ("99999999999e-3", Ok("99999999.999")),
592 ("99999999991e-3", Ok("99999999.991")),
593 (
597 "111111111111111111111111111111111111111111e-34",
598 Ok("11111111.1111111111111111111111111111111"),
599 ),
600 (
604 "1.23456788901234567890123456789012345678890123456",
605 Ok("1.23456788901234567890123456789012345678"),
606 ),
607 ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
609 ("0e999999999999999", Ok("0")),
611 ("1e-999999999999999", Ok("0")),
613 (
617 "111111111111111111111111111111111111111111e2147483644",
618 Err(ParseDecimalError::OutOfRange),
619 ),
620 (
623 ".1111111111111111111111111111111111111111e-2147483648",
624 Ok("0"),
625 ),
626 ("123e5", Ok("12300000")),
627 ("123E4", Ok("1230000")),
628 ("123e3", Ok("123000")),
629 ("123e2", Ok("12300")),
630 ("123e1", Ok("1230")),
631 ("123e0", Ok("123")),
632 ("123e-1", Ok("12.3")),
633 ("123e-2", Ok("1.23")),
634 (".123", Ok("0.123")),
635 (".124", Ok("0.124")),
636 (".125", Ok("0.125")),
637 (".126", Ok("0.126")),
638 (".133", Ok("0.133")),
639 (".134", Ok("0.134")),
640 (".135", Ok("0.135")),
641 (".136", Ok("0.136")),
642 ("1e38", Ok("100000000000000000000000000000000000000")),
643 ("1e39", Err(ParseDecimalError::OutOfRange)),
644 (
645 "1e-255",
646 Ok(
647 "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
648 ),
649 ),
650 ("1e-256", Ok("0")),
651 ] {
652 println!("{s}: {:?}", s.parse::<DynamicDecimal>());
653 assert_eq!(
654 s.parse::<DynamicDecimal>().map(|d| d.to_string()),
655 expect.map(|d| d.to_string())
656 );
657 }
658 }
659
660 #[test]
661 fn to_integer() {
662 for x in -9999..=9999 {
663 let f = DynamicDecimal::new(x, 1);
664 assert_eq!(i128::from(f), x / 10);
665 assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
666 assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
667 assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
668 assert_eq!(
669 i8::try_from(f).ok(),
670 (-1289..=1279).contains(&x).then_some((x / 10) as i8)
671 );
672 assert_eq!(
673 u128::try_from(f).ok(),
674 (x > -10).then_some((x / 10) as u128)
675 );
676 assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
677 assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
678 assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
679 assert_eq!(
680 u8::try_from(f).ok(),
681 (-9..=2559).contains(&x).then_some((x / 10) as u8)
682 );
683 }
684
685 assert_eq!(i128::from(DynamicDecimal::new(1, 40)), 0);
686 assert_eq!(i128::from(DynamicDecimal::new(i128::MAX, 0)), i128::MAX);
687 assert_eq!(i64::try_from(DynamicDecimal::new(1, 40)), Ok(0));
688 assert_eq!(
689 i64::try_from(DynamicDecimal::new(i128::MAX, 0)),
690 Err(OutOfRange)
691 );
692 assert_eq!(
693 i64::try_from(DynamicDecimal::new(i128::MIN, 0)),
694 Err(OutOfRange)
695 );
696 }
697
698 #[test]
699 fn mul() {
700 fn f(n: f64) -> DynamicDecimal {
701 DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
702 }
703
704 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 assert_eq!((f(-1.23) * f(-2.34)).trunc_digits(2), f(2.87));
710
711 for a in -999..=999 {
713 let af: DynamicDecimal = DynamicDecimal::new(a, 2);
714 for b in -999..=999 {
715 let bf = DynamicDecimal::new(b, 2);
716 assert_eq!(af * bf, DynamicDecimal::new(a * b, 4));
717 }
718 }
719 }
720
721 #[test]
722 fn add() {
723 fn f(n: f64) -> DynamicDecimal {
724 DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
725 }
726
727 assert_eq!(f(1.23) + f(2.34), f(3.57));
729 assert_eq!(f(-1.23) + f(2.34), f(1.11));
730 assert_eq!(f(1.23) + f(-2.34), f(-1.11));
731 assert_eq!(f(-1.23) + f(-2.34), f(-3.57));
732
733 for a in -999..=999 {
734 let af = DynamicDecimal::new(a, 2);
735 for b in -999..=999 {
736 let bf = DynamicDecimal::new(b, 2);
737 assert_eq!(af + bf, DynamicDecimal::new(a + b, 2));
738 }
739 }
740 }
741
742 #[test]
743 fn sub() {
744 fn f(n: f64) -> DynamicDecimal {
745 DynamicDecimal::try_from(n).unwrap().trunc_digits(2)
746 }
747
748 assert_eq!(f(1.23) - f(2.34), f(-1.11));
749 assert_eq!(f(-1.23) - f(2.34), f(-3.57));
750 assert_eq!(f(1.23) - f(-2.34), f(3.57));
751 assert_eq!(f(-1.23) - f(-2.34), f(1.11));
752
753 for a in -999..=999 {
754 let af = DynamicDecimal::new(a, 2);
755 for b in -999..=999 {
756 let bf = DynamicDecimal::new(b, 2);
757 assert_eq!(af - bf, DynamicDecimal::new(a - b, 2));
758 }
759 }
760 }
761
762 #[test]
763 fn div() {
764 fn f(n: f64) -> DynamicDecimal {
765 DynamicDecimal::try_from(n).unwrap().trunc_digits(6)
766 }
767
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 assert_eq!(f(-1.23) / f(-2.34), f(0.525641));
772
773 for a in -999..=999 {
774 let af = DynamicDecimal::new(a, 2);
775 for b in -999..=999 {
776 let bf = DynamicDecimal::new(b, 2);
777 if b != 0 {
778 let expected = DynamicDecimal::new(a * 1000000 / b, 6);
779 assert_eq!(af / bf, expected);
780 }
781 }
782 }
783 }
784}