1#[cfg(feature = "schemars")]
2use alloc::string::ToString;
3use alloc::{
4 fmt::{Debug, Display},
5 format,
6 str::FromStr,
7 string::String,
8 vec::Vec,
9};
10#[cfg(feature = "schemars")]
11use core::fmt::Write as _;
12use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
13
14use primitive_types::U512;
15
16pub const FRACTIONAL_BITS: usize = 128;
17pub const FRACTIONAL_DECIMAL_DIGITS: usize = 38;
19pub const WHOLE_DECIMAL_DIGITS: usize = 115;
21
22const MAX_WHOLE: U512 = U512([
23 u64::MAX,
24 u64::MAX,
25 u64::MAX,
26 u64::MAX,
27 u64::MAX,
28 u64::MAX,
29 0,
30 0,
31]);
32
33#[cfg(feature = "schemars")]
34fn decimal_whole_pattern(include_maximum: bool) -> String {
35 let maximum = MAX_WHOLE.to_string();
36 let bytes = maximum.as_bytes();
37 let mut branches = Vec::with_capacity(bytes.len() + 2);
38 branches.push("0".to_string());
39 branches.push("[1-9][0-9]{0,114}".to_string());
40
41 for (index, &digit) in bytes.iter().enumerate() {
42 let minimum = if index == 0 { b'1' } else { b'0' };
43 if digit > minimum {
44 let mut branch = maximum[..index].to_string();
45 if digit == minimum + 1 {
46 branch.push(char::from(minimum));
47 } else {
48 branch.push('[');
49 branch.push(char::from(minimum));
50 branch.push('-');
51 branch.push(char::from(digit - 1));
52 branch.push(']');
53 }
54 let remaining = bytes.len() - index - 1;
55 match remaining {
56 0 => {}
57 1 => branch.push_str("[0-9]"),
58 _ => write!(&mut branch, "[0-9]{{{remaining}}}").unwrap(),
59 }
60 branches.push(branch);
61 }
62 }
63 if include_maximum {
64 branches.push(maximum);
65 }
66 branches.join("|")
67}
68
69fn u512_pow10(mut exponent: u32) -> U512 {
71 let mut y = U512::one();
72 let mut x = U512::from(10);
73
74 while exponent > 1 {
75 if exponent % 2 == 1 {
76 y *= x;
77 }
78 x *= x;
79 exponent >>= 1;
80 }
81
82 x * y
83}
84
85#[macro_export]
86macro_rules! dec {
87 ($s:literal) => {
88 <$crate::number::Decimal as core::str::FromStr>::from_str($s).unwrap()
89 };
90}
91
92#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
93pub struct Decimal {
94 repr: U512,
95}
96
97impl Default for Decimal {
98 fn default() -> Self {
99 Self::ZERO
100 }
101}
102
103#[cfg(feature = "schemars")]
104impl schemars::JsonSchema for Decimal {
105 fn schema_name() -> String {
106 "Decimal".to_string()
107 }
108
109 fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
110 let mut schema = gen.subschema_for::<String>().into_object();
111 schema.metadata().description = Some("512-bit fixed-precision decimal".to_string());
112 schema.string().pattern = Some(format!(
113 "^(?:{})(\\.[0-9]{{1,38}})?$",
114 decimal_whole_pattern(true),
115 ));
116 schema.into()
117 }
118}
119
120#[cfg(feature = "borsh")]
121impl borsh::BorshSchema for Decimal {
122 fn add_definitions_recursively(
123 definitions: &mut alloc::collections::BTreeMap<
124 borsh::schema::Declaration,
125 borsh::schema::Definition,
126 >,
127 ) {
128 <[u64; 8] as borsh::BorshSchema>::add_definitions_recursively(definitions);
129 }
130
131 fn declaration() -> borsh::schema::Declaration {
132 String::from("Decimal")
133 }
134}
135
136#[cfg(feature = "borsh")]
137impl borsh::BorshSerialize for Decimal {
138 fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
139 borsh::BorshSerialize::serialize(&self.repr.0, writer)
140 }
141}
142
143#[cfg(feature = "borsh")]
144impl borsh::BorshDeserialize for Decimal {
145 fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
146 Ok(Self {
147 repr: U512(borsh::BorshDeserialize::deserialize_reader(reader)?),
148 })
149 }
150}
151
152#[cfg(feature = "serde")]
153impl serde::Serialize for Decimal {
154 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
155 where
156 S: serde::Serializer,
157 {
158 serializer.serialize_str(&self.to_fixed(FRACTIONAL_DECIMAL_DIGITS))
159 }
160}
161
162#[cfg(feature = "serde")]
163impl<'de> serde::Deserialize<'de> for Decimal {
164 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
165 where
166 D: serde::Deserializer<'de>,
167 {
168 let s = <String as serde::Deserialize>::deserialize(deserializer)?;
169 Decimal::from_str(&s).map_err(serde::de::Error::custom)
170 }
171}
172
173impl Decimal {
174 const REPR_EPSILON: U512 = U512([0b1000, 0, 0, 0, 0, 0, 0, 0]);
177
178 pub const MAX: Self = Self { repr: U512::MAX };
179 pub const MIN: Self = Self { repr: U512::zero() };
180
181 pub const ZERO: Self = Self { repr: U512::zero() };
182 pub const ONE_HALF: Self = Self {
183 repr: U512([0, 0x8000_0000_0000_0000, 0, 0, 0, 0, 0, 0]),
184 };
185 #[rustfmt::skip]
186 pub const LN2: Self = Self {
187 repr: U512([0xC9E3_B398_03F2_F6B0, 0xB172_17F7_D1CF_79AB, 0, 0, 0, 0, 0, 0]),
188 };
189 pub const ONE: Self = Self {
190 repr: U512([0, 0, 1, 0, 0, 0, 0, 0]),
191 };
192 pub const TWO: Self = Self {
193 repr: U512([0, 0, 2, 0, 0, 0, 0, 0]),
194 };
195 #[rustfmt::skip]
196 pub const E: Self = Self {
197 repr: U512([0xBF71_5880_9CF4_F3C9, 0xB7E1_5162_8AED_2A6A, 2, 0, 0, 0, 0, 0]),
198 };
199
200 pub fn as_repr(self) -> [u64; 8] {
201 self.repr.0
202 }
203
204 pub const fn from_repr(repr: [u64; 8]) -> Self {
205 Self { repr: U512(repr) }
206 }
207
208 #[must_use]
216 pub fn quantize(self) -> Self {
217 if self.repr > U512::MAX - (Self::REPR_EPSILON >> 1) {
218 return Self::MAX;
219 }
220 Self {
221 repr: Self::epsilon_round(self.repr),
222 }
223 }
224
225 pub fn is_zero(&self) -> bool {
226 self.repr.is_zero()
227 }
228
229 pub fn near_equal(self, other: Self) -> bool {
230 self.abs_diff(other).repr <= Self::REPR_EPSILON
231 }
232
233 #[must_use]
234 pub fn pow(self, mut exponent: i32) -> Self {
235 if exponent == 0 {
236 return Self::ONE;
237 }
238
239 let exponent_is_negative = if exponent < 0 {
240 exponent = -exponent;
241 true
242 } else {
243 false
244 };
245
246 let mut y = Self::ONE;
247 let mut x = self;
248
249 while exponent > 1 {
250 if exponent % 2 == 1 {
251 y *= x;
252 }
253 x *= x;
254 exponent >>= 1;
255 }
256
257 let result = x * y;
258
259 if exponent_is_negative {
260 Decimal::ONE / result
261 } else {
262 result
263 }
264 }
265
266 pub fn pow2_int(exponent: u32) -> Option<Self> {
268 #[allow(clippy::cast_possible_truncation)]
269 if exponent > 512 - FRACTIONAL_BITS as u32 {
270 None
271 } else {
272 Some(Self {
273 repr: Self::ONE.repr << exponent,
274 })
275 }
276 }
277
278 fn pow2_frac(self) -> Self {
279 const MAX_ITERATIONS: u32 = 35; debug_assert!(self <= Self::ONE);
281
282 let mut sum = Self::ONE;
283 let mut term = Self::ONE;
284 let numerator = self * Self::LN2;
285
286 for n in 1..=MAX_ITERATIONS {
287 term *= numerator / n;
288 if term == Self::ZERO {
289 break;
290 }
291 sum += &term;
292 }
293
294 sum
295 }
296
297 pub fn pow2(self) -> Option<Self> {
298 let whole = u32::try_from(self.to_u128_floor()?).ok()?;
299 let frac = self - whole;
300
301 Some(Self::pow2_int(whole)? * Self::pow2_frac(frac))
302 }
303
304 #[must_use]
305 pub fn mul_pow10(self, exponent: i32) -> Option<Self> {
306 if exponent == 0 || self.is_zero() {
307 return Some(self);
308 }
309
310 let abs_exponent = exponent.abs_diff(0);
311 if (abs_exponent as usize) > WHOLE_DECIMAL_DIGITS + FRACTIONAL_DECIMAL_DIGITS {
312 return None;
313 }
314
315 if exponent >= 0 {
316 let operand = u512_pow10(abs_exponent);
317 let (repr, overflowed) = self.repr.overflowing_mul(operand);
318 if !overflowed {
319 return Some(Self { repr });
320 }
321 } else {
322 let operand = u512_pow10(abs_exponent);
323 let repr = self.repr / operand;
324 if !repr.is_zero() {
325 return Some(Self { repr });
326 }
327 }
328
329 None
330 }
331
332 #[must_use]
333 pub fn abs_diff(self, other: Self) -> Self {
334 if self > other {
335 self - other
336 } else {
337 other - self
338 }
339 }
340
341 pub fn to_u128_floor(self) -> Option<u128> {
342 let truncated = self.repr >> FRACTIONAL_BITS;
343 if truncated.bits() <= 128 {
344 Some(truncated.as_u128())
345 } else {
346 None
347 }
348 }
349
350 pub fn to_u128_ceil(self) -> Option<u128> {
351 let truncated = self.repr >> FRACTIONAL_BITS;
352 if truncated.bits() <= 128 {
353 if self.fractional_part().is_zero() {
354 Some(truncated.as_u128())
355 } else {
356 truncated.as_u128().checked_add(1)
357 }
358 } else {
359 None
360 }
361 }
362
363 #[allow(
364 clippy::cast_precision_loss,
365 clippy::cast_possible_truncation,
366 clippy::cast_possible_wrap,
367 reason = "Lossiness is acceptable for this function"
368 )]
369 pub fn to_f64_lossy(self) -> f64 {
370 let frac = self.repr.low_u128() as f64 / f64_pow2(FRACTIONAL_BITS as i32);
371 let low = (self.repr >> FRACTIONAL_BITS).low_u128() as f64;
372 let high = (self.repr >> (FRACTIONAL_BITS * 2)).low_u128() as f64 * f64_pow2(128);
373
374 high + low + frac
375 }
376
377 pub fn to_fixed(&self, precision: usize) -> String {
378 let precision = precision.min(FRACTIONAL_DECIMAL_DIGITS);
379 let (fractional_part, overflow) = self.fractional_part_to_dec_string(precision, false);
380 let fractional_part_trimmed = fractional_part.trim_end_matches('0');
381 let repr = if overflow {
382 self.repr.saturating_add(Self::ONE.repr)
383 } else {
384 self.repr
385 };
386 if fractional_part_trimmed.is_empty() {
387 format!("{}", repr >> FRACTIONAL_BITS)
388 } else {
389 format!("{}.{fractional_part_trimmed}", repr >> FRACTIONAL_BITS)
390 }
391 }
392
393 fn fractional_part(&self) -> U512 {
394 U512([self.repr.0[0], self.repr.0[1], 0, 0, 0, 0, 0, 0])
395 }
396
397 pub fn fractional_part_as_u128_dividend(&self) -> u128 {
398 u128::from(self.repr.0[0]) | (u128::from(self.repr.0[1]) << 64)
399 }
400
401 fn epsilon_round(repr: U512) -> U512 {
402 (repr + (Self::REPR_EPSILON >> 1)) & !(Self::REPR_EPSILON - 1)
403 }
404
405 fn fractional_part_to_dec_string(&self, precision: usize, round_up: bool) -> (String, bool) {
406 let mut s = Vec::with_capacity(precision);
407 let mut f = self.fractional_part();
408 let mut overflow = false;
409
410 if round_up {
411 let plus_two = f.saturating_add(2.into());
412 overflow = plus_two.0[2] != 0;
413 f = U512([plus_two.0[0], plus_two.0[1], 0, 0, 0, 0, 0, 0]);
414 }
415
416 for _ in 0..precision {
417 if f.is_zero() {
418 break;
419 }
420
421 f *= 10;
422
423 let digit = (f / Self::ONE.repr).low_u64();
424 #[allow(clippy::cast_possible_truncation)]
425 s.push(digit as u8 + b'0');
426
427 f %= Self::ONE.repr;
428 }
429
430 if !round_up && !f.is_zero() && (U512::MAX - 2 >= self.repr) {
431 return self.fractional_part_to_dec_string(precision, true);
432 }
433
434 (unsafe { String::from_utf8_unchecked(s) }, overflow)
436 }
437}
438
439#[inline]
440#[allow(clippy::cast_sign_loss)]
441const fn f64_pow2(exponent: i32) -> f64 {
443 debug_assert!(
444 !(exponent < -1022 || exponent > 1023),
445 "Exponent out of range for f64"
446 );
447 f64::from_bits(((1023 + exponent) as u64) << 52)
448}
449
450pub mod error {
451 use thiserror::Error;
452
453 #[derive(Debug, Error)]
454 #[error("Failed to parse decimal")]
455 pub struct DecimalParseError;
456}
457
458impl FromStr for Decimal {
459 type Err = error::DecimalParseError;
460
461 fn from_str(s: &str) -> Result<Self, Self::Err> {
462 let (whole, frac) = match s.split_once('.') {
463 Some((whole, frac)) if !frac.contains('.') => (whole, Some(frac)),
464 Some(_) => return Err(error::DecimalParseError),
465 None => (s, None),
466 };
467
468 let canonical_whole = whole == "0"
469 || whole
470 .as_bytes()
471 .split_first()
472 .is_some_and(|(&first, rest)| {
473 first.is_ascii_digit() && first != b'0' && rest.iter().all(u8::is_ascii_digit)
474 });
475 if !canonical_whole {
476 return Err(error::DecimalParseError);
477 }
478
479 if let Some(frac) = frac {
480 if frac.is_empty()
481 || frac.len() > FRACTIONAL_DECIMAL_DIGITS
482 || !frac.as_bytes().iter().all(u8::is_ascii_digit)
483 {
484 return Err(error::DecimalParseError);
485 }
486 }
487
488 let whole = U512::from_dec_str(whole).map_err(|_| error::DecimalParseError)?;
489 if whole > MAX_WHOLE {
490 return Err(error::DecimalParseError);
491 }
492 let whole = whole << FRACTIONAL_BITS;
493
494 let Some(frac) = frac else {
495 return Ok(Self { repr: whole });
496 };
497
498 let mut fractional = U512::zero();
499 let mut divisor = 10u128;
500 for digit in frac.bytes().map(|digit| digit - b'0') {
501 if digit != 0 {
502 fractional += (U512::from(digit) << (FRACTIONAL_BITS * 2)) / divisor;
503 }
504 if let Some(next_divisor) = divisor.checked_mul(10) {
505 divisor = next_divisor;
506 }
507 }
508 let fractional = Decimal::epsilon_round(fractional >> FRACTIONAL_BITS);
509 let (repr, overflowed) = whole.overflowing_add(fractional);
510 if overflowed {
511 return Ok(Self::MAX);
512 }
513
514 Ok(Self { repr })
515 }
516}
517
518impl Display for Decimal {
519 fn fmt(&self, f: &mut alloc::fmt::Formatter<'_>) -> alloc::fmt::Result {
520 write!(f, "{}", self.to_f64_lossy())
521 }
522}
523
524impl Debug for Decimal {
525 fn fmt(&self, f: &mut alloc::fmt::Formatter<'_>) -> alloc::fmt::Result {
526 write!(f, "{}", self.to_fixed(FRACTIONAL_DECIMAL_DIGITS))
527 }
528}
529
530macro_rules! impl_self {
531 ($s:ty,$t:ty) => {
532 impl Add<$t> for $s {
533 type Output = Decimal;
534
535 fn add(self, rhs: $t) -> Decimal {
536 Decimal {
537 repr: self.repr.add(rhs.repr),
538 }
539 }
540 }
541
542 impl Sub<$t> for $s {
543 type Output = Decimal;
544
545 fn sub(self, rhs: $t) -> Decimal {
546 Decimal {
547 repr: self.repr.sub(rhs.repr),
548 }
549 }
550 }
551
552 impl Mul<$t> for $s {
553 type Output = Decimal;
554
555 fn mul(self, rhs: $t) -> Decimal {
556 #[allow(clippy::cast_possible_truncation)]
557 let mut shr = FRACTIONAL_BITS as u32;
558 let shr_self = self.repr.trailing_zeros().min(shr);
559 let self_repr = self.repr >> shr_self;
560 shr -= shr_self;
561 let shr_rhs = rhs.repr.trailing_zeros().min(shr);
562 let rhs_repr = rhs.repr >> shr_rhs;
563 shr -= shr_rhs;
564 Decimal {
565 repr: (self_repr * rhs_repr) >> shr,
566 }
567 }
568 }
569
570 impl Div<$t> for $s {
571 type Output = Decimal;
572
573 fn div(self, rhs: $t) -> Decimal {
574 #[allow(clippy::cast_possible_truncation)]
575 let mut sh = FRACTIONAL_BITS as u32;
576 let sh_self = self.repr.leading_zeros().min(sh);
577 let self_repr = self.repr << sh_self;
578 sh -= sh_self;
579 let sh_rhs = rhs.repr.trailing_zeros().min(sh);
580 let rhs_repr = rhs.repr >> sh_rhs;
581 sh -= sh_rhs;
582 Decimal {
583 repr: (self_repr / rhs_repr) << sh,
584 }
585 }
586 }
587 };
588}
589
590impl_self!(Decimal, Decimal);
591impl_self!(&Decimal, Decimal);
592impl_self!(Decimal, &Decimal);
593impl_self!(&Decimal, &Decimal);
594
595macro_rules! impl_self_assign {
596 ($s:ty,$t:ty) => {
597 impl AddAssign<$t> for $s {
598 fn add_assign(&mut self, rhs: $t) {
599 self.repr += rhs.repr;
600 }
601 }
602
603 impl SubAssign<$t> for $s {
604 fn sub_assign(&mut self, rhs: $t) {
605 self.repr -= rhs.repr;
606 }
607 }
608
609 impl DivAssign<$t> for $s {
610 fn div_assign(&mut self, rhs: $t) {
611 self.repr = (*self / rhs).repr;
612 }
613 }
614
615 impl MulAssign<$t> for $s {
616 fn mul_assign(&mut self, rhs: $t) {
617 self.repr = (*self * rhs).repr;
618 }
619 }
620 };
621}
622
623impl_self_assign!(Decimal, Decimal);
624impl_self_assign!(Decimal, &Decimal);
625
626macro_rules! impl_int {
627 ($t:ty) => {
628 impl_int!(@from $t);
629 impl_int!(@ops $t, Decimal);
630 impl_int!(@ops $t, &Decimal);
631 };
632
633 (@from $t:ty) => {
634 impl From<$t> for Decimal {
635 fn from(value: $t) -> Self {
636 Self {
637 repr: U512::from(value) << FRACTIONAL_BITS,
638 }
639 }
640 }
641 };
642
643 (@ops $t:ty,$s:ty) => {
644 impl Mul<$t> for $s {
645 type Output = Decimal;
646
647 fn mul(self, rhs: $t) -> Decimal {
648 Decimal { repr: self.repr * U512::from(rhs) }
649 }
650 }
651
652 impl Mul<$s> for $t {
653 type Output = Decimal;
654
655 fn mul(self, rhs: $s) -> Decimal {
656 Decimal { repr: U512::from(self) * rhs.repr }
657 }
658 }
659
660 impl Div<$t> for $s {
661 type Output = Decimal;
662
663 fn div(self, rhs: $t) -> Decimal {
664 Decimal { repr: self.repr / U512::from(rhs) }
665 }
666 }
667
668 impl Div<$s> for $t {
669 type Output = Decimal;
670
671 fn div(self, rhs: $s) -> Decimal {
672 Decimal::from(self) / rhs
673 }
674 }
675
676 impl Add<$t> for $s {
677 type Output = Decimal;
678
679 fn add(self, rhs: $t) -> Decimal {
680 self + Decimal::from(rhs)
681 }
682 }
683
684 impl Add<$s> for $t {
685 type Output = Decimal;
686
687 fn add(self, rhs: $s) -> Decimal {
688 Decimal::from(self) + rhs
689 }
690 }
691
692 impl Sub<$t> for $s {
693 type Output = Decimal;
694
695 fn sub(self, rhs: $t) -> Decimal {
696 self - Decimal::from(rhs)
697 }
698 }
699
700 impl Sub<$s> for $t {
701 type Output = Decimal;
702
703 fn sub(self, rhs: $s) -> Decimal {
704 Decimal::from(self) - rhs
705 }
706 }
707
708 impl PartialEq<$t> for $s {
709 fn eq(&self, other: &$t) -> bool {
710 self.repr == Decimal::from(*other).repr
711 }
712 }
713
714 impl PartialOrd<$t> for $s {
715 fn partial_cmp(&self, other: &$t) -> Option<core::cmp::Ordering> {
716 self.repr.partial_cmp(&Decimal::from(*other).repr)
717 }
718 }
719 };
720}
721
722impl_int!(u8);
723impl_int!(u16);
724impl_int!(u32);
725impl_int!(u64);
726impl_int!(u128);
727impl_int!(::primitive_types::U256);
728
729macro_rules! impl_from_const {
730 ($t:ty,$name:ident) => {
731 impl Decimal {
732 pub const fn $name(value: $t) -> Self {
733 Self {
734 repr: U512([0, 0, value as u64, 0, 0, 0, 0, 0]),
735 }
736 }
737 }
738 };
739}
740
741impl_from_const!(u8, from_u8);
742impl_from_const!(u16, from_u16);
743impl_from_const!(u32, from_u32);
744impl_from_const!(u64, from_u64);
745
746#[cfg(test)]
747mod tests {
748 use alloc::string::ToString;
749 use primitive_types::U256;
750 use rand::Rng;
751 use rstest::rstest;
752
753 use super::*;
754
755 macro_rules! println {
756 ($($arg:tt)*) => {
757 #[cfg(feature = "std")]
758 std::println!($($arg)*);
759 #[cfg(not(feature = "std"))]
760 let _ = format_args!($($arg)*);
761 };
762 }
763
764 fn with_upper_u128(n: u128) -> Decimal {
769 let mut d = Decimal::from(n);
770 d *= Decimal::from(u128::pow(2, 64));
771 d *= Decimal::from(u128::pow(2, 64));
772 d
773 }
774
775 fn get_upper_u128(mut d: Decimal) -> u128 {
776 d /= Decimal::from(u128::pow(2, 64));
777 d /= Decimal::from(u128::pow(2, 64));
778 d.to_u128_floor().unwrap()
779 }
780
781 #[rstest]
782 #[test]
783 fn const_constructors_are_correct() {
784 assert_eq!(Decimal::from_u8(0).to_u128_ceil().unwrap(), 0);
785 assert_eq!(Decimal::from_u8(u8::MAX).to_u128_ceil().unwrap(), 0xff);
786 assert_eq!(Decimal::from_u16(0).to_u128_ceil().unwrap(), 0);
787 assert_eq!(Decimal::from_u16(u16::MAX).to_u128_ceil().unwrap(), 0xffff);
788 assert_eq!(Decimal::from_u32(0).to_u128_ceil().unwrap(), 0);
789 assert_eq!(
790 Decimal::from_u32(u32::MAX).to_u128_ceil().unwrap(),
791 0xffff_ffff,
792 );
793 assert_eq!(Decimal::from_u64(0).to_u128_ceil().unwrap(), 0);
794 assert_eq!(
795 Decimal::from_u64(u64::MAX).to_u128_ceil().unwrap(),
796 0xffff_ffff_ffff_ffff,
797 );
798 }
799
800 #[rstest]
801 #[case(0, 0)]
802 #[case(0, 1)]
803 #[case(1, 0)]
804 #[case(1, 1)]
805 #[case(2_934_570_000_008_u128, 9_595_959_283_u128)]
806 #[case(u128::MAX, 0)]
807 #[case(0, u128::MAX)]
808 #[test]
809 fn addition(#[case] a: u128, #[case] b: u128) {
810 assert_eq!(Decimal::from(a) + Decimal::from(b), a + b);
811 assert_eq!(
812 get_upper_u128(with_upper_u128(a) + with_upper_u128(b)),
813 a + b,
814 );
815 }
816
817 #[rstest]
818 #[case(0, 0)]
819 #[case(1, 0)]
820 #[case(1, 1)]
821 #[case(2_934_570_000_008_u128, 9_595_959_283_u128)]
822 #[case(u128::MAX, 0)]
823 #[case(u128::MAX, 1)]
824 #[case(u128::MAX, u128::MAX / 2)]
825 #[case(u128::MAX, u128::MAX)]
826 #[test]
827 fn subtraction(#[case] a: u128, #[case] b: u128) {
828 assert_eq!(Decimal::from(a) - Decimal::from(b), a - b);
829 assert_eq!(
830 get_upper_u128(with_upper_u128(a) - with_upper_u128(b)),
831 a - b,
832 );
833 }
834
835 #[rstest]
836 #[case(0, 0)]
837 #[case(0, 1)]
838 #[case(1, 0)]
839 #[case(1, 1)]
840 #[case(2, 2)]
841 #[case(u128::MAX, 0)]
842 #[case(u128::MAX, 1)]
843 #[case(0, u128::MAX)]
844 #[case(1, u128::MAX)]
845 #[test]
846 fn multiplication(#[case] a: u128, #[case] b: u128) {
847 assert_eq!(Decimal::from(a) * Decimal::from(b), a * b);
848 assert_eq!(get_upper_u128(with_upper_u128(a) * b), a * b);
849 assert_eq!(get_upper_u128(a * with_upper_u128(b)), a * b);
850 }
851
852 #[rstest]
853 #[case(0, 1)]
854 #[case(1, 1)]
855 #[case(1, 2)]
856 #[case(u128::MAX, u128::MAX)]
857 #[case(u128::MAX, 1)]
858 #[case(0, u128::MAX)]
859 #[case(1, u128::MAX)]
860 #[case(1, 10)]
861 #[case(3, 10_000)]
862 #[test]
863 fn division(#[case] a: u128, #[case] b: u128) {
864 #[allow(clippy::cast_precision_loss)]
865 let quotient = a as f64 / b as f64;
866 let abs_difference_lte = |d: Decimal, f: f64| (d.to_f64_lossy() - f).abs() <= 1e-200;
867 assert!(abs_difference_lte(
868 Decimal::from(a) / Decimal::from(b),
869 quotient,
870 ));
871 assert!(abs_difference_lte(
872 with_upper_u128(a) / with_upper_u128(b),
873 quotient,
874 ));
875 }
876
877 #[rstest]
878 #[case(12, 2)]
879 #[case(2, 32)]
880 #[case(1, 0)]
881 #[case(0, 0)]
882 #[case(0, 1)]
883 #[case(1, 1)]
884 #[test]
885 fn power(#[case] x: u128, #[case] n: u32) {
886 #[allow(clippy::cast_possible_wrap)]
887 let n_i32 = n as i32;
888 assert_eq!(Decimal::from(x).pow(n_i32), Decimal::from(x.pow(n)));
889 }
890
891 #[test]
892 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
893 fn pow10_valid_range() {
894 assert_eq!(
895 Decimal::ONE.mul_pow10(-(FRACTIONAL_DECIMAL_DIGITS as i32) - 1),
896 None,
897 );
898 for i in -(FRACTIONAL_DECIMAL_DIGITS as i32)..=(WHOLE_DECIMAL_DIGITS as i32) {
899 println!("10^{i} = {:?}", Decimal::ONE.mul_pow10(i).unwrap());
900 }
901 assert_eq!(
902 Decimal::ONE.mul_pow10((WHOLE_DECIMAL_DIGITS as i32) + 1),
903 None,
904 );
905 }
906
907 #[rstest]
908 #[case(0, 0)]
909 #[case(0, 1)]
910 #[case(0, -1)]
911 #[case(1, 0)]
912 #[case(1, 1)]
913 #[case(1, -1)]
914 #[case(1, i32::try_from(WHOLE_DECIMAL_DIGITS).unwrap())]
915 #[case(1, i32::try_from(FRACTIONAL_DECIMAL_DIGITS).unwrap())]
916 #[case(1, -i32::try_from(FRACTIONAL_DECIMAL_DIGITS).unwrap())]
917 #[case(12, 20)]
918 #[case(12, 0)]
919 #[case(12, -20)]
920 #[case(u128::MAX, 0)]
921 #[case(u128::MAX, -20)]
922 #[test]
923 fn mul_pow10(#[case] x: u128, #[case] n: i32) {
924 #[allow(clippy::cast_sign_loss)]
925 if n >= 0 {
926 assert_eq!(
927 Decimal::from(x).mul_pow10(n).unwrap(),
928 Decimal::from(x) * Decimal::from(10u32).pow(n),
929 );
930 } else {
931 assert!(Decimal::from(x)
932 .mul_pow10(n)
933 .unwrap()
934 .near_equal(Decimal::from(x) / U256::exp10(-n as usize)));
935 }
936 }
937
938 #[test]
939 fn constants_are_accurate() {
940 assert_eq!(Decimal::ZERO.to_u128_floor().unwrap(), 0);
941 assert!((Decimal::ONE_HALF.to_f64_lossy() - 0.5_f64).abs() < 1e-200);
942 assert_eq!(Decimal::ONE.to_u128_floor().unwrap(), 1);
943 assert_eq!(Decimal::TWO.to_u128_floor().unwrap(), 2);
944 }
945
946 #[rstest]
947 #[case(Decimal::ONE, 0)]
948 #[case(Decimal::ONE_HALF, 1u128 << 127)]
949 #[test]
950 fn get_fractional_dividend(#[case] value: Decimal, #[case] expected: u128) {
951 assert_eq!(value.fractional_part_as_u128_dividend(), expected);
952 }
953
954 #[cfg(feature = "serde")]
955 #[rstest]
956 #[case(Decimal::ONE)]
957 #[case(Decimal::TWO)]
958 #[case(Decimal::ZERO)]
959 #[case(Decimal::ONE_HALF)]
960 #[case(Decimal::from(u128::MAX))]
961 #[case(Decimal::from(u64::MAX) / Decimal::from(u128::MAX))]
962 #[case(Decimal::MAX)]
963 #[test]
964 fn serialization(#[case] value: Decimal) {
965 let serialized = serde_json::to_string(&value).unwrap();
966 let deserialized: Decimal = serde_json::from_str(&serialized).unwrap();
967
968 assert!(value.near_equal(deserialized));
969 }
970
971 #[test]
972 fn from_self_string_serialization_precision() {
973 const ITERATIONS: usize = 1_024;
974 const TRANSFORMATIONS: usize = 16;
975
976 let mut rng = rand::thread_rng();
977
978 let mut max_error = U512::zero();
979 let mut error_distribution = [0u32; 16];
980 let mut value_with_max_error = Decimal::ZERO;
981
982 #[allow(clippy::cast_possible_truncation)]
983 for _ in 0..ITERATIONS {
984 let actual = Decimal {
985 repr: U512(rng.gen()),
986 };
987
988 let mut s = actual.to_fixed(FRACTIONAL_DECIMAL_DIGITS);
989 for _ in 0..(TRANSFORMATIONS - 1) {
990 s = Decimal::from_str(&s)
991 .unwrap()
992 .to_fixed(FRACTIONAL_DECIMAL_DIGITS);
993 }
994 let parsed = Decimal::from_str(&s).unwrap();
995
996 let e = actual.abs_diff(parsed).repr;
997
998 if e > max_error {
999 max_error = e;
1000 value_with_max_error = actual;
1001 }
1002
1003 error_distribution[e.0[0] as usize] += 1;
1004 }
1005
1006 println!("Error distribution:");
1007 for (i, x) in error_distribution.iter().enumerate() {
1008 println!("\t{i}: {x:b}");
1009 }
1010 println!("Max error: {:?}", max_error.0);
1011
1012 assert!(
1013 max_error <= Decimal::REPR_EPSILON,
1014 "Stringification error of repr {:?} is repr {:?}",
1015 value_with_max_error.repr.0,
1016 max_error.0,
1017 );
1018 }
1019
1020 #[test]
1021 #[allow(clippy::cast_precision_loss)]
1022 fn from_f64_string_serialization_precision() {
1023 const ITERATIONS: usize = 10_000;
1024 let mut rng = rand::thread_rng();
1025 let epsilon = Decimal {
1026 repr: Decimal::REPR_EPSILON,
1027 }
1028 .to_f64_lossy();
1029
1030 let t = |f: f64| {
1031 let actual = f.abs();
1032 let string = actual.to_string();
1033 let parsed = Decimal::from_str(&string).unwrap();
1034
1035 let e = (parsed.to_f64_lossy() - actual).abs();
1036
1037 assert!(e <= epsilon, "Stringification error of f64 {actual} is {e}");
1038 };
1039
1040 for _ in 0..ITERATIONS {
1041 t(rng.gen::<f64>() * rng.gen::<u128>() as f64);
1042 }
1043 }
1044
1045 #[test]
1046 fn hal_29_rejects_noncanonical_or_partial_decimal_text() {
1047 let malformed = [
1048 "",
1049 ".1",
1050 "1.",
1051 "01",
1052 "+1",
1053 "-1",
1054 " 1",
1055 "1 ",
1056 "1e1",
1057 "1_0",
1058 "1.0.0",
1059 "1.000000000000000000000000000000000000000",
1060 "١",
1061 ];
1062
1063 for value in malformed {
1064 assert!(Decimal::from_str(value).is_err(), "{value:?} was accepted");
1065 }
1066 }
1067
1068 #[test]
1069 fn decimal_max_fixed_text_round_trips() {
1070 assert_eq!(
1071 Decimal::MAX
1072 .to_fixed(FRACTIONAL_DECIMAL_DIGITS)
1073 .parse::<Decimal>()
1074 .unwrap(),
1075 Decimal::MAX
1076 );
1077 }
1078
1079 #[test]
1080 fn hal_34_enforces_the_exact_whole_range() {
1081 let maximum = MAX_WHOLE.to_string();
1082 assert!(Decimal::from_str(&maximum).is_ok());
1083 assert!(Decimal::from_str(&format!("{maximum}.1")).is_ok());
1084
1085 let first_out_of_range = (MAX_WHOLE + U512::one()).to_string();
1086 assert!(Decimal::from_str(&first_out_of_range).is_err());
1087 assert!(Decimal::from_str(&U512::MAX.to_string()).is_err());
1088
1089 let carrying_fraction = format!("{maximum}.99999999999999999999999999999999999999");
1090 assert_eq!(Decimal::from_str(&carrying_fraction).unwrap(), Decimal::MAX);
1091 }
1092
1093 #[cfg(feature = "serde")]
1094 #[test]
1095 fn hal_34_serde_uses_decimal_range_validation() {
1096 let first_out_of_range = (MAX_WHOLE + U512::one()).to_string();
1097 let encoded = serde_json::to_string(&first_out_of_range).unwrap();
1098 assert!(serde_json::from_str::<Decimal>(&encoded).is_err());
1099
1100 let carrying_fraction = format!("{MAX_WHOLE}.99999999999999999999999999999999999999");
1101 let encoded = serde_json::to_string(&carrying_fraction).unwrap();
1102 assert_eq!(
1103 serde_json::from_str::<Decimal>(&encoded).unwrap(),
1104 Decimal::MAX
1105 );
1106 }
1107
1108 #[cfg(feature = "schemars")]
1109 #[test]
1110 fn hal_34_schema_matches_decimal_parser_boundaries() {
1111 let schema = schemars::schema_for!(Decimal);
1112 let pattern = schema
1113 .schema
1114 .string
1115 .as_ref()
1116 .unwrap()
1117 .pattern
1118 .as_ref()
1119 .unwrap();
1120 let regex = regex::Regex::new(pattern).unwrap();
1121 let maximum = MAX_WHOLE.to_string();
1122 let cases = [
1123 ("0".to_string(), true),
1124 ("1.0".to_string(), true),
1125 (maximum.clone(), true),
1126 (
1127 format!("{maximum}.99999999999999999999999999999999999999"),
1128 true,
1129 ),
1130 ((MAX_WHOLE + U512::one()).to_string(), false),
1131 (U512::MAX.to_string(), false),
1132 ("01".to_string(), false),
1133 ("1.".to_string(), false),
1134 ("1e1".to_string(), false),
1135 ];
1136
1137 for (value, expected) in cases {
1138 assert_eq!(Decimal::from_str(&value).is_ok(), expected, "{value}");
1139 assert_eq!(regex.is_match(&value), expected, "{value}");
1140 }
1141 }
1142
1143 #[test]
1144 fn quantize_preserves_parsed_values() {
1145 for text in [
1146 "0",
1147 "0.1",
1148 "0.01",
1149 "0.00000000000000000000000000000000000001",
1150 "0.99999999999999999999999999999999999999",
1151 "1",
1152 "1.6958947224456518",
1153 "9007199254740993.1",
1154 ] {
1155 let value: Decimal = text.parse().unwrap();
1156 assert_eq!(value.quantize(), value, "{text}");
1157 }
1158 assert_eq!(Decimal::MAX.quantize(), Decimal::MAX);
1159 }
1160
1161 #[test]
1162 fn quantize_rounds_to_the_parsing_grid() {
1163 for (repr, expected) in [(0, 0), (3, 0), (4, 8), (7, 8), (8, 8), (11, 8), (12, 16)] {
1164 let value = Decimal {
1165 repr: U512::from(repr),
1166 };
1167 assert_eq!(value.quantize().repr, U512::from(expected));
1168 }
1169 let derived = Decimal::from(100_000u32) / Decimal::from(1_000_000u32);
1170 assert_eq!(derived.quantize(), dec!("0.1"));
1171 }
1172
1173 #[test]
1174 fn quantize_is_monotonic_idempotent_and_saturating() {
1175 for base in [
1176 U512::zero(),
1177 Decimal::ONE.repr - U512::from(16),
1178 U512::MAX - U512::from(32),
1179 ] {
1180 let mut previous = Decimal::ZERO;
1181 for offset in 0..=32 {
1182 let value = Decimal {
1183 repr: base + U512::from(offset),
1184 };
1185 let rounded = value.quantize();
1186 assert!(previous <= rounded);
1187 assert_eq!(rounded.quantize(), rounded);
1188 assert!(rounded.abs_diff(value).repr <= U512::from(4));
1189 assert!(
1190 rounded == Decimal::MAX || rounded.repr % Decimal::REPR_EPSILON == U512::zero()
1191 );
1192 previous = rounded;
1193 }
1194 }
1195 for distance in 0..=3 {
1196 let value = Decimal {
1197 repr: U512::MAX - U512::from(distance),
1198 };
1199 assert_eq!(value.quantize(), Decimal::MAX);
1200 }
1201 assert_eq!(
1202 Decimal {
1203 repr: U512::MAX - U512::from(4),
1204 }
1205 .quantize()
1206 .repr,
1207 U512::MAX - U512::from(7)
1208 );
1209 }
1210
1211 #[test]
1212 fn round_up_repr() {
1213 let cases = [
1214 Decimal {
1215 #[rustfmt::skip]
1216 repr: U512([ 0x0966_4E4C_9169_501F, 0xB226_2812_5CF2_3CD0, 1, 0, 0, 0, 0, 0 ]),
1217 },
1218 Decimal {
1219 repr: U512([u64::MAX, u64::MAX, 1, 0, 0, 0, 0, 0]),
1220 },
1222 Decimal {
1223 repr: U512([u64::MAX - 1, u64::MAX, 1, 0, 0, 0, 0, 0]),
1224 },
1225 Decimal { repr: U512::zero() },
1226 Decimal::MAX,
1227 ];
1228
1229 for case in cases {
1230 let p: Decimal = case.to_fixed(FRACTIONAL_DECIMAL_DIGITS).parse().unwrap();
1231
1232 println!("{:x?}", case.repr.0);
1233 println!("{:x?}", p.repr.0);
1234 println!("|{p:?} - {case:?}| = {:?}", p.abs_diff(case).as_repr());
1235
1236 assert!(p.near_equal(case));
1237 }
1238 }
1239
1240 #[test]
1241 fn round_up_str() {
1242 let cases = [
1244 "1",
1245 "0",
1246 "1.6958947224456518",
1247 "2.79",
1248 "0.6",
1249 "10.6",
1250 "0.01",
1251 "0.599999999999999999999999999999999999",
1252 ];
1253 for case in cases {
1254 println!("Testing {case}...");
1255 let n = Decimal::from_str(case).unwrap();
1256 let s = n.to_fixed(FRACTIONAL_DECIMAL_DIGITS);
1257 let parsed = Decimal::from_str(&s).unwrap();
1258 assert_eq!(n, parsed);
1259 println!("{n:?}");
1260 println!("");
1261 }
1262 }
1263
1264 #[test]
1265 #[allow(clippy::float_cmp)]
1266 fn const_pow2() {
1267 for i in -1022..=1023 {
1268 let f = f64_pow2(i);
1269 let e = 2f64.powi(i);
1270 assert_eq!(f, e);
1271 }
1272 }
1273}