1#![allow(
11 clippy::cast_possible_truncation,
12 clippy::cast_possible_wrap,
13 clippy::cast_sign_loss
14)]
15
16use core::cmp::Ordering;
17use core::fmt;
18use core::hash::{Hash, Hasher};
19use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
20use core::str::FromStr;
21
22use serde::{Deserialize, Serialize};
23
24use crate::validate::{Validate, ValidationPath, Violations};
25
26#[derive(Clone, Copy, Default)]
116pub struct Decimal {
117 mantissa: i64,
118 scale: u8,
119}
120
121const POW10_U64: [u64; 19] = [
123 1,
124 10,
125 100,
126 1_000,
127 10_000,
128 100_000,
129 1_000_000,
130 10_000_000,
131 100_000_000,
132 1_000_000_000,
133 10_000_000_000,
134 100_000_000_000,
135 1_000_000_000_000,
136 10_000_000_000_000,
137 100_000_000_000_000,
138 1_000_000_000_000_000,
139 10_000_000_000_000_000,
140 100_000_000_000_000_000,
141 1_000_000_000_000_000_000,
142];
143
144const fn pow10_i128(exp: u32) -> i128 {
146 let mut result: i128 = 1;
147 let mut left = exp;
148 while left > 0 {
149 result *= 10;
150 left -= 1;
151 }
152 result
153}
154
155const ACCUMULATE_LIMIT: u128 = u128::MAX / 16;
157
158impl Decimal {
159 pub const ZERO: Self = Self {
161 mantissa: 0,
162 scale: 0,
163 };
164
165 pub const ONE: Self = Self {
167 mantissa: 1,
168 scale: 0,
169 };
170
171 pub const MAX_SCALE: u8 = 18;
173
174 #[must_use]
181 pub const fn new(mantissa: i64, scale: u8) -> Self {
182 assert!(
183 scale <= Self::MAX_SCALE,
184 "a Decimal scale may not exceed Decimal::MAX_SCALE"
185 );
186 Self { mantissa, scale }
187 }
188
189 #[must_use]
191 pub const fn try_new(mantissa: i64, scale: u8) -> Option<Self> {
192 if scale > Self::MAX_SCALE {
193 return None;
194 }
195 Some(Self { mantissa, scale })
196 }
197
198 #[must_use]
200 pub const fn from_i64(value: i64) -> Self {
201 Self {
202 mantissa: value,
203 scale: 0,
204 }
205 }
206
207 #[must_use]
209 pub const fn mantissa(self) -> i64 {
210 self.mantissa
211 }
212
213 #[must_use]
218 pub const fn scale(self) -> u8 {
219 self.scale
220 }
221
222 #[must_use]
224 pub const fn is_zero(self) -> bool {
225 self.mantissa == 0
226 }
227
228 #[must_use]
230 pub const fn signum(self) -> i32 {
231 if self.mantissa < 0 {
232 -1
233 } else if self.mantissa > 0 {
234 1
235 } else {
236 0
237 }
238 }
239
240 #[must_use]
243 pub const fn eq_exact(self, other: Self) -> bool {
244 self.mantissa == other.mantissa && self.scale == other.scale
245 }
246
247 #[must_use]
249 pub const fn normalized(mut self) -> Self {
250 while self.scale > 0 && self.mantissa % 10 == 0 {
251 self.mantissa /= 10;
252 self.scale -= 1;
253 }
254 if self.mantissa == 0 {
255 self.scale = 0;
256 }
257 self
258 }
259
260 #[must_use]
265 pub const fn rescale(self, scale: u8) -> Option<Self> {
266 if scale > Self::MAX_SCALE {
267 return None;
268 }
269 if scale == self.scale {
270 return Some(self);
271 }
272 if scale > self.scale {
273 let factor = POW10_U64[(scale - self.scale) as usize];
274 let Some(mantissa) = self.mantissa.checked_mul(factor as i64) else {
275 return None;
276 };
277 return Some(Self { mantissa, scale });
278 }
279 let factor = POW10_U64[(self.scale - scale) as usize] as i64;
280 if self.mantissa % factor != 0 {
281 return None;
282 }
283 Some(Self {
284 mantissa: self.mantissa / factor,
285 scale,
286 })
287 }
288
289 #[must_use]
292 pub const fn round_to(self, scale: u8) -> Option<Self> {
293 if scale >= self.scale {
294 return self.rescale(scale);
295 }
296 let drop = (self.scale - scale) as u32;
297 let negative = self.mantissa < 0;
298 let magnitude = self.mantissa.unsigned_abs() as u128;
299 let rounded = round_off(magnitude, drop, false);
300 if rounded > i64::MAX as u128 {
301 return None;
302 }
303 let mantissa = rounded as i64;
304 Some(Self {
305 mantissa: if negative { -mantissa } else { mantissa },
306 scale,
307 })
308 }
309
310 #[must_use]
323 pub const fn trunc_to(self, scale: u8) -> Option<Self> {
324 if scale >= self.scale {
325 return self.rescale(scale);
326 }
327 let drop = (self.scale - scale) as u32;
328 if drop > 38 {
329 return Some(Self { mantissa: 0, scale });
330 }
331 let divisor = pow10_i128(drop);
333 Some(Self {
334 mantissa: (self.mantissa as i128 / divisor) as i64,
335 scale,
336 })
337 }
338
339 #[must_use]
343 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
344 let scale = if self.scale > rhs.scale {
345 self.scale
346 } else {
347 rhs.scale
348 };
349 let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
350 return None;
351 };
352 narrow(a + b, scale)
353 }
354
355 #[must_use]
360 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
361 let scale = if self.scale > rhs.scale {
362 self.scale
363 } else {
364 rhs.scale
365 };
366 let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
367 return None;
368 };
369 narrow(a - b, scale)
370 }
371
372 #[must_use]
374 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
375 let scale = self.scale as u32 + rhs.scale as u32;
376 let product = self.mantissa as i128 * rhs.mantissa as i128;
377 if scale <= Self::MAX_SCALE as u32 {
378 return narrow(product, scale as u8);
379 }
380 let drop = scale - Self::MAX_SCALE as u32;
382 let negative = product < 0;
383 let rounded = round_off(product.unsigned_abs(), drop, false);
384 if rounded > i64::MAX as u128 {
385 return None;
386 }
387 let mantissa = rounded as i64;
388 Some(Self {
389 mantissa: if negative { -mantissa } else { mantissa },
390 scale: Self::MAX_SCALE,
391 })
392 }
393
394 #[must_use]
400 pub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self> {
401 if rhs.mantissa == 0 || scale > Self::MAX_SCALE {
402 return None;
403 }
404 let shift = scale as i32 + rhs.scale as i32 - self.scale as i32;
406 let negative = (self.mantissa < 0) != (rhs.mantissa < 0);
407 let mut numerator = self.mantissa.unsigned_abs() as u128;
408 let denominator = rhs.mantissa.unsigned_abs() as u128;
409 let shift = shift + 1;
411 let mut extra_drop = 0u32;
412 if shift >= 0 {
413 let up = shift as u32;
414 if up > 38 {
415 return None;
416 }
417 let factor = pow10_i128(up) as u128;
418 let Some(scaled) = numerator.checked_mul(factor) else {
419 return None;
420 };
421 numerator = scaled;
422 } else {
423 let down = (-shift) as u32;
426 if down > 38 {
427 return None;
428 }
429 extra_drop = down;
430 }
431 let quotient = if extra_drop > 0 {
432 let factor = pow10_i128(extra_drop) as u128;
433 let Some(scaled) = denominator.checked_mul(factor) else {
434 return None;
435 };
436 numerator / scaled
437 } else {
438 numerator / denominator
439 };
440 let remainder_is_zero = if extra_drop > 0 {
441 let factor = pow10_i128(extra_drop) as u128;
442 match denominator.checked_mul(factor) {
443 Some(scaled) => numerator.is_multiple_of(scaled),
444 None => return None,
445 }
446 } else {
447 numerator.is_multiple_of(denominator)
448 };
449 let rounded = round_off(quotient, 1, !remainder_is_zero);
450 if rounded > i64::MAX as u128 {
451 return None;
452 }
453 let mantissa = rounded as i64;
454 Some(Self {
455 mantissa: if negative { -mantissa } else { mantissa },
456 scale,
457 })
458 }
459
460 #[must_use]
467 pub const fn checked_pow10(self, exp: i32) -> Option<Self> {
468 if exp == 0 {
469 return Some(self);
470 }
471 if exp > 40 || exp < -40 {
475 return if self.mantissa == 0 {
476 Some(Self::ZERO)
477 } else {
478 None
479 };
480 }
481 if exp < 0 {
482 let want = self.scale as i32 - exp;
484 if want <= Self::MAX_SCALE as i32 {
485 return Some(Self {
486 mantissa: self.mantissa,
487 scale: want as u8,
488 });
489 }
490 let surplus = want - Self::MAX_SCALE as i32;
492 let surplus = surplus as u32;
493 if surplus > 18 {
494 return None;
495 }
496 let factor = POW10_U64[surplus as usize] as i64;
497 if self.mantissa % factor != 0 {
498 return None;
499 }
500 return Some(Self {
501 mantissa: self.mantissa / factor,
502 scale: Self::MAX_SCALE,
503 });
504 }
505 let mut left = exp as u32;
507 let mut mantissa = self.mantissa;
508 let mut scale = self.scale;
509 while left > 0 && scale > 0 {
510 scale -= 1;
511 left -= 1;
512 }
513 while left > 0 {
514 let step = if left > 18 { 18 } else { left };
515 let Some(next) = mantissa.checked_mul(POW10_U64[step as usize] as i64) else {
516 return None;
517 };
518 mantissa = next;
519 left -= step;
520 }
521 Some(Self { mantissa, scale })
522 }
523
524 #[must_use]
526 pub const fn checked_abs(self) -> Option<Self> {
527 let Some(mantissa) = self.mantissa.checked_abs() else {
528 return None;
529 };
530 Some(Self {
531 mantissa,
532 scale: self.scale,
533 })
534 }
535
536 #[must_use]
538 pub const fn checked_neg(self) -> Option<Self> {
539 let Some(mantissa) = self.mantissa.checked_neg() else {
540 return None;
541 };
542 Some(Self {
543 mantissa,
544 scale: self.scale,
545 })
546 }
547
548 #[must_use]
550 pub const fn min(self, other: Self) -> Self {
551 match self.compare(other) {
552 Ordering::Greater => other,
553 _ => self,
554 }
555 }
556
557 #[must_use]
559 pub const fn max(self, other: Self) -> Self {
560 match self.compare(other) {
561 Ordering::Less => other,
562 _ => self,
563 }
564 }
565
566 #[must_use]
568 pub const fn compare(self, other: Self) -> Ordering {
569 let scale = if self.scale > other.scale {
570 self.scale
571 } else {
572 other.scale
573 };
574 match (self.to_i128_at(scale), other.to_i128_at(scale)) {
575 (Some(a), Some(b)) => {
576 if a < b {
577 Ordering::Less
578 } else if a > b {
579 Ordering::Greater
580 } else {
581 Ordering::Equal
582 }
583 }
584 _ => {
587 if self.mantissa < other.mantissa {
588 Ordering::Less
589 } else if self.mantissa > other.mantissa {
590 Ordering::Greater
591 } else {
592 Ordering::Equal
593 }
594 }
595 }
596 }
597
598 const fn to_i128_at(self, scale: u8) -> Option<i128> {
600 if scale < self.scale {
601 return None;
602 }
603 let factor = pow10_i128((scale - self.scale) as u32);
604 Some(self.mantissa as i128 * factor)
605 }
606
607 #[allow(clippy::too_many_lines)]
627 pub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError> {
628 let n = bytes.len();
629 let mut i = 0usize;
630 while i < n && is_space(bytes[i]) {
631 i += 1;
632 }
633 let mut negative = false;
634 if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
635 negative = bytes[i] == b'-';
636 i += 1;
637 }
638
639 let mut magnitude: u128 = 0;
640 let mut fraction_digits: i64 = 0;
641 let mut skipped_integer_digits: i64 = 0;
642 let mut round_digit: u8 = 0;
643 let mut sticky = false;
644 let mut dropped_any = false;
645 let mut seen_digit = false;
646 let mut seen_point = false;
647
648 while i < n {
649 let byte = bytes[i];
650 if byte == b'.' {
651 if seen_point {
652 return Err(ParseDecimalError::Invalid);
653 }
654 seen_point = true;
655 i += 1;
656 continue;
657 }
658 if byte < b'0' || byte > b'9' {
659 break;
660 }
661 seen_digit = true;
662 let digit = byte - b'0';
663 if magnitude < ACCUMULATE_LIMIT {
664 magnitude = magnitude * 10 + digit as u128;
665 if seen_point {
666 fraction_digits += 1;
667 }
668 } else {
669 if !seen_point {
671 skipped_integer_digits += 1;
672 }
673 if dropped_any {
674 if digit != 0 {
675 sticky = true;
676 }
677 } else {
678 round_digit = digit;
679 dropped_any = true;
680 }
681 }
682 i += 1;
683 }
684 if !seen_digit {
685 return Err(ParseDecimalError::Invalid);
686 }
687 let mut rounded_off = false;
688 if dropped_any {
689 if round_digit > 5 || (round_digit == 5 && (sticky || magnitude % 2 == 1)) {
690 magnitude += 1;
691 }
692 rounded_off = true;
693 }
694
695 let mut exponent: i64 = 0;
696 if i < n && (bytes[i] == b'e' || bytes[i] == b'E') {
697 i += 1;
698 let mut exponent_negative = false;
699 if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
700 exponent_negative = bytes[i] == b'-';
701 i += 1;
702 }
703 let mut seen_exponent_digit = false;
704 while i < n && bytes[i] >= b'0' && bytes[i] <= b'9' {
705 seen_exponent_digit = true;
706 if exponent < 1_000_000 {
708 exponent = exponent * 10 + (bytes[i] - b'0') as i64;
709 }
710 i += 1;
711 }
712 if !seen_exponent_digit {
713 return Err(ParseDecimalError::Invalid);
714 }
715 if exponent_negative {
716 exponent = -exponent;
717 }
718 }
719 while i < n && is_space(bytes[i]) {
720 i += 1;
721 }
722 if i != n {
723 return Err(ParseDecimalError::Invalid);
724 }
725
726 let mut scale = fraction_digits - skipped_integer_digits - exponent;
728 if magnitude == 0 {
729 if scale < 0 || scale > Self::MAX_SCALE as i64 {
732 scale = 0;
733 }
734 return Ok(Self {
735 mantissa: 0,
736 scale: scale as u8,
737 });
738 }
739
740 if scale < 0 {
741 let shift = -scale;
742 if shift > 38 {
743 return Err(ParseDecimalError::Overflow);
744 }
745 let factor = pow10_i128(shift as u32) as u128;
746 let Some(scaled) = magnitude.checked_mul(factor) else {
747 return Err(ParseDecimalError::Overflow);
748 };
749 magnitude = scaled;
750 scale = 0;
751 } else if scale > Self::MAX_SCALE as i64 {
752 let drop = scale - Self::MAX_SCALE as i64;
753 if drop > 39 {
754 magnitude = 0;
755 } else {
756 let dropped = drop as u32;
757 magnitude = round_off(magnitude, dropped, false);
758 }
759 scale = Self::MAX_SCALE as i64;
760 rounded_off = true;
761 }
762
763 while magnitude > i64::MAX as u128 {
765 if scale == 0 {
766 return Err(ParseDecimalError::Overflow);
767 }
768 magnitude = round_off(magnitude, 1, false);
769 scale -= 1;
770 rounded_off = true;
771 }
772 let _ = rounded_off;
773 let mantissa = magnitude as i64;
774 Ok(Self {
775 mantissa: if negative { -mantissa } else { mantissa },
776 scale: scale as u8,
777 })
778 }
779
780 #[must_use]
792 pub const fn from_literal(text: &str) -> Self {
793 let bytes = text.as_bytes();
794 let mut digits = [0u8; 64];
796 let mut len = 0usize;
797 let mut i = 0usize;
798 while i < bytes.len() {
799 if bytes[i] != b'_' {
800 assert!(len < 64, "decimal literal is too long");
801 digits[len] = bytes[i];
802 len += 1;
803 }
804 i += 1;
805 }
806 let (kept, _) = digits.split_at(len);
807 match Self::from_ascii(kept) {
808 Ok(value) => value,
809 Err(ParseDecimalError::Invalid) => panic!("not a decimal number"),
810 Err(ParseDecimalError::Overflow) => panic!("decimal number out of range"),
811 }
812 }
813
814 #[must_use]
822 #[allow(clippy::cast_precision_loss)] pub fn to_f64_lossy(self) -> f64 {
824 const POW10_F64: [f64; 19] = [
825 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
826 1e16, 1e17, 1e18,
827 ];
828 let mantissa = self.mantissa as f64;
829 mantissa / POW10_F64[self.scale as usize]
830 }
831
832 #[must_use]
840 pub fn from_f64_lossy(value: f64) -> Option<Self> {
841 if !value.is_finite() {
842 return None;
843 }
844 let mut buffer = TextBuffer::new();
845 if fmt::Write::write_fmt(&mut buffer, format_args!("{value:e}")).is_err() {
848 return None;
849 }
850 Self::from_ascii(buffer.as_bytes()).ok()
851 }
852}
853
854const fn round_off(magnitude: u128, digits: u32, sticky: bool) -> u128 {
859 if digits == 0 {
860 return magnitude;
861 }
862 if digits > 38 {
863 return 0;
864 }
865 let divisor = pow10_i128(digits) as u128;
866 let quotient = magnitude / divisor;
867 let remainder = magnitude % divisor;
868 let half = divisor / 2;
869 if remainder > half || (remainder == half && (sticky || quotient % 2 == 1)) {
870 quotient + 1
871 } else {
872 quotient
873 }
874}
875
876const fn narrow(mantissa: i128, scale: u8) -> Option<Decimal> {
878 if mantissa > i64::MAX as i128 || mantissa < i64::MIN as i128 {
879 return None;
880 }
881 Some(Decimal {
882 mantissa: mantissa as i64,
883 scale,
884 })
885}
886
887const fn is_space(byte: u8) -> bool {
888 matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
889}
890
891#[derive(Clone, Copy, Debug, PartialEq, Eq)]
893#[non_exhaustive]
894pub enum ParseDecimalError {
895 Invalid,
897 Overflow,
899}
900
901impl fmt::Display for ParseDecimalError {
902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 f.write_str(match self {
904 ParseDecimalError::Invalid => "not a decimal number",
905 ParseDecimalError::Overflow => "decimal number out of range",
906 })
907 }
908}
909
910#[cfg(feature = "std")]
911impl std::error::Error for ParseDecimalError {}
912
913impl FromStr for Decimal {
914 type Err = ParseDecimalError;
915
916 fn from_str(text: &str) -> Result<Self, Self::Err> {
917 Self::from_ascii(text.as_bytes())
918 }
919}
920
921impl fmt::Debug for Decimal {
922 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
925 write!(f, "Decimal({self})")
926 }
927}
928
929impl fmt::Display for Decimal {
930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
932 if self.scale == 0 {
933 return write!(f, "{}", self.mantissa);
934 }
935 let magnitude = self.mantissa.unsigned_abs();
936 let divisor = POW10_U64[self.scale as usize];
937 let sign = if self.mantissa < 0 { "-" } else { "" };
938 write!(
939 f,
940 "{sign}{}.{:0width$}",
941 magnitude / divisor,
942 magnitude % divisor,
943 width = self.scale as usize
944 )
945 }
946}
947
948impl PartialEq for Decimal {
953 fn eq(&self, other: &Self) -> bool {
954 self.compare(*other) == Ordering::Equal
955 }
956}
957
958impl Eq for Decimal {}
959
960impl PartialOrd for Decimal {
961 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
962 Some(self.cmp(other))
963 }
964}
965
966impl Ord for Decimal {
967 fn cmp(&self, other: &Self) -> Ordering {
968 self.compare(*other)
969 }
970}
971
972impl Hash for Decimal {
973 fn hash<H: Hasher>(&self, state: &mut H) {
975 let normalized = self.normalized();
976 normalized.mantissa.hash(state);
977 normalized.scale.hash(state);
978 }
979}
980
981macro_rules! binary_op {
986 ($trait:ident, $method:ident, $checked:ident, $what:literal) => {
987 impl $trait for Decimal {
988 type Output = Decimal;
989 fn $method(self, rhs: Decimal) -> Decimal {
993 self.$checked(rhs)
994 .expect(concat!("Decimal ", $what, " overflowed"))
995 }
996 }
997 };
998}
999
1000binary_op!(Add, add, checked_add, "addition");
1001binary_op!(Sub, sub, checked_sub, "subtraction");
1002binary_op!(Mul, mul, checked_mul, "multiplication");
1003
1004impl Div for Decimal {
1005 type Output = Decimal;
1006
1007 fn div(self, rhs: Decimal) -> Decimal {
1014 self.checked_div(rhs, Decimal::MAX_SCALE)
1015 .expect("Decimal division by zero or overflow")
1016 }
1017}
1018
1019impl Neg for Decimal {
1020 type Output = Decimal;
1021
1022 fn neg(self) -> Decimal {
1026 self.checked_neg().expect("Decimal negation overflowed")
1027 }
1028}
1029
1030impl AddAssign for Decimal {
1031 fn add_assign(&mut self, rhs: Decimal) {
1032 *self = *self + rhs;
1033 }
1034}
1035
1036impl SubAssign for Decimal {
1037 fn sub_assign(&mut self, rhs: Decimal) {
1038 *self = *self - rhs;
1039 }
1040}
1041
1042impl core::iter::Sum for Decimal {
1043 fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
1044 iter.fold(Decimal::ZERO, |total, value| total + value)
1045 }
1046}
1047
1048macro_rules! from_integer {
1053 ($($ty:ty),*) => {
1054 $(
1055 impl From<$ty> for Decimal {
1056 fn from(value: $ty) -> Self {
1057 Self { mantissa: i64::from(value), scale: 0 }
1058 }
1059 }
1060 )*
1061 };
1062}
1063
1064from_integer!(i8, i16, i32, i64, u8, u16, u32);
1065
1066impl TryFrom<u64> for Decimal {
1067 type Error = ParseDecimalError;
1068
1069 fn try_from(value: u64) -> Result<Self, Self::Error> {
1070 i64::try_from(value)
1071 .map(Self::from_i64)
1072 .map_err(|_| ParseDecimalError::Overflow)
1073 }
1074}
1075
1076impl TryFrom<Decimal> for i64 {
1077 type Error = ParseDecimalError;
1078
1079 fn try_from(value: Decimal) -> Result<Self, Self::Error> {
1081 value
1082 .rescale(0)
1083 .map(Decimal::mantissa)
1084 .ok_or(ParseDecimalError::Invalid)
1085 }
1086}
1087
1088const TEXT_CAPACITY: usize = 40;
1094
1095struct TextBuffer {
1096 bytes: [u8; TEXT_CAPACITY],
1097 len: usize,
1098}
1099
1100impl TextBuffer {
1101 const fn new() -> Self {
1102 Self {
1103 bytes: [0; TEXT_CAPACITY],
1104 len: 0,
1105 }
1106 }
1107
1108 fn as_bytes(&self) -> &[u8] {
1109 &self.bytes[..self.len]
1110 }
1111
1112 fn as_str(&self) -> &str {
1113 core::str::from_utf8(self.as_bytes()).unwrap_or("0")
1116 }
1117}
1118
1119impl fmt::Write for TextBuffer {
1120 fn write_str(&mut self, text: &str) -> fmt::Result {
1121 let end = self.len + text.len();
1122 if end > TEXT_CAPACITY {
1123 return Err(fmt::Error);
1124 }
1125 self.bytes[self.len..end].copy_from_slice(text.as_bytes());
1126 self.len = end;
1127 Ok(())
1128 }
1129}
1130
1131const RAW_TOKEN: &str = "$serde_json::private::RawValue";
1142
1143impl Serialize for Decimal {
1144 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1147 use serde::ser::SerializeStruct as _;
1148 let mut buffer = TextBuffer::new();
1149 if fmt::Write::write_fmt(&mut buffer, format_args!("{self}")).is_err() {
1150 return Err(serde::ser::Error::custom("decimal is too long to render"));
1151 }
1152 let mut raw = serializer.serialize_struct(RAW_TOKEN, 1)?;
1153 raw.serialize_field(RAW_TOKEN, buffer.as_str())?;
1154 raw.end()
1155 }
1156}
1157
1158impl<'de> Deserialize<'de> for Decimal {
1159 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1160 deserializer.deserialize_newtype_struct(RAW_TOKEN, DecimalVisitor)
1161 }
1162}
1163
1164struct DecimalVisitor;
1165
1166impl<'de> serde::de::Visitor<'de> for DecimalVisitor {
1167 type Value = Decimal;
1168
1169 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1170 f.write_str("a JSON number")
1171 }
1172
1173 fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Decimal, E> {
1174 Ok(Decimal::from_i64(value))
1175 }
1176
1177 fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Decimal, E> {
1178 Decimal::try_from(value).map_err(|_| E::custom("number out of range for a decimal"))
1179 }
1180
1181 fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Decimal, E> {
1182 Decimal::from_f64_lossy(value)
1183 .ok_or_else(|| E::custom("number is not a finite decimal in range"))
1184 }
1185
1186 fn visit_newtype_struct<D: serde::Deserializer<'de>>(
1189 self,
1190 deserializer: D,
1191 ) -> Result<Decimal, D::Error> {
1192 deserializer.deserialize_any(DecimalVisitor)
1193 }
1194
1195 fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Decimal, A::Error> {
1198 use serde::de::Error as _;
1199 let Some(RawKey) = map.next_key::<RawKey>()? else {
1200 return Err(A::Error::custom("expected a JSON number"));
1201 };
1202 let RawToken(value) = map.next_value::<RawToken>()?;
1203 Ok(value)
1204 }
1205}
1206
1207struct RawKey;
1209
1210impl<'de> Deserialize<'de> for RawKey {
1211 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1212 struct KeyVisitor;
1213 impl serde::de::Visitor<'_> for KeyVisitor {
1214 type Value = RawKey;
1215 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216 f.write_str("a raw value marker")
1217 }
1218 fn visit_str<E: serde::de::Error>(self, _value: &str) -> Result<RawKey, E> {
1219 Ok(RawKey)
1220 }
1221 }
1222 deserializer.deserialize_identifier(KeyVisitor)
1223 }
1224}
1225
1226struct RawToken(Decimal);
1228
1229impl<'de> Deserialize<'de> for RawToken {
1230 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1231 struct TokenVisitor;
1232 impl serde::de::Visitor<'_> for TokenVisitor {
1233 type Value = RawToken;
1234
1235 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236 f.write_str("a JSON number")
1237 }
1238
1239 fn visit_str<E: serde::de::Error>(self, token: &str) -> Result<RawToken, E> {
1240 use serde::de::Unexpected;
1241 let trimmed = token.trim();
1246 let unexpected = match trimmed.as_bytes().first() {
1247 Some(b'"') => Some(Unexpected::Str(trimmed.trim_matches('"'))),
1248 Some(b'{') => Some(Unexpected::Map),
1249 Some(b'[') => Some(Unexpected::Seq),
1250 Some(b't') => Some(Unexpected::Bool(true)),
1251 Some(b'f') => Some(Unexpected::Bool(false)),
1252 Some(b'n') => Some(Unexpected::Unit),
1253 _ => None,
1254 };
1255 if let Some(unexpected) = unexpected {
1256 return Err(E::invalid_type(unexpected, &"a JSON number"));
1257 }
1258 Decimal::from_ascii(trimmed.as_bytes())
1259 .map(RawToken)
1260 .map_err(|error| {
1261 let expected: &str = match error {
1262 ParseDecimalError::Overflow => "a decimal number in range",
1263 ParseDecimalError::Invalid => "a decimal number",
1264 };
1265 E::invalid_value(Unexpected::Other(trimmed), &expected)
1266 })
1267 }
1268 }
1269 deserializer.deserialize_str(TokenVisitor)
1270 }
1271}
1272
1273impl Validate for Decimal {
1274 fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
1277}
1278
1279#[macro_export]
1296macro_rules! decimal {
1297 ($($token:tt)+) => {
1298 const {
1299 $crate::types::Decimal::from_literal(::core::stringify!($($token)+))
1300 }
1301 };
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306 use super::*;
1307
1308 #[test]
1309 fn trunc_to_drops_toward_zero_and_never_rounds_up() {
1310 let d = |s: &str| s.parse::<Decimal>().unwrap();
1311 assert_eq!(d("1234.7").trunc_to(0), Some(d("1234")));
1312 assert_eq!(d("1234.5").trunc_to(0), Some(d("1234")));
1313 assert_eq!(d("1234.99999").trunc_to(2), Some(d("1234.99")));
1314 assert_eq!(d("-1.9").trunc_to(0), Some(d("-1")));
1315 assert_eq!(d("-0.5").trunc_to(0), Some(d("0")));
1316 assert_eq!(d("12").trunc_to(2).map(Decimal::scale), Some(2));
1317 assert!(d("12").trunc_to(2).unwrap().eq_exact(d("12.00")));
1318 assert_eq!(
1319 Decimal::new(i64::MAX, 18).trunc_to(0),
1320 Some(Decimal::from(9))
1321 );
1322 assert_eq!(
1323 Decimal::new(i64::MIN, 0).trunc_to(0),
1324 Some(Decimal::new(i64::MIN, 0))
1325 );
1326 }
1327 use alloc::string::ToString;
1328
1329 #[test]
1330 fn the_scale_the_station_sent_survives_the_round_trip() {
1331 let value: Decimal = serde_json::from_str("2935.600").unwrap();
1334 assert_eq!(value.scale(), 3);
1335 assert_eq!(value.mantissa(), 2_935_600);
1336 assert_eq!(serde_json::to_string(&value).unwrap(), "2935.600");
1337 assert_eq!(value.to_string(), "2935.600");
1338
1339 let short: Decimal = serde_json::from_str("2935.6").unwrap();
1341 assert_eq!(value, short);
1342 assert!(!value.eq_exact(short));
1343 }
1344
1345 #[test]
1346 fn a_difference_of_two_registers_is_exact() {
1347 let start: Decimal = "0.1".parse().unwrap();
1349 let stop: Decimal = "10.2".parse().unwrap();
1350 assert_eq!((stop - start).to_string(), "10.1");
1351 }
1352
1353 #[test]
1354 fn every_json_number_spelling_parses() {
1355 for (text, expected) in [
1356 ("0", "0"),
1357 ("-0", "0"),
1358 ("42", "42"),
1359 ("-17.25", "-17.25"),
1360 ("0.00", "0.00"),
1361 ("1e3", "1000"),
1362 ("1.5E+3", "1500"),
1363 ("15e-1", "1.5"),
1364 ("2E-4", "0.0002"),
1365 ("0.000000000000000001", "0.000000000000000001"),
1366 ("9223372036854775807", "9223372036854775807"),
1367 ] {
1368 let value: Decimal = text.parse().unwrap_or_else(|_| panic!("{text}"));
1369 assert_eq!(value.to_string(), expected, "{text}");
1370 }
1371 for text in ["", "-", "abc", "1.2.3", "1e", "NaN", "1 2", "--1"] {
1372 assert!(text.parse::<Decimal>().is_err(), "{text} should not parse");
1373 }
1374 }
1375
1376 #[test]
1377 fn excess_precision_rounds_half_to_even_rather_than_failing() {
1378 let value: Decimal = "0.12345678901234567895".parse().unwrap();
1380 assert_eq!(value.scale(), Decimal::MAX_SCALE);
1381 assert_eq!(value.to_string(), "0.123456789012345679");
1382 assert_eq!("1e30".parse::<Decimal>(), Err(ParseDecimalError::Overflow));
1384 }
1385
1386 #[test]
1387 fn arithmetic_is_exact_and_checked() {
1388 let a = decimal!(1.05);
1389 let b = decimal!(2.1);
1390 assert_eq!((a + b).to_string(), "3.15");
1391 assert_eq!((b - a).to_string(), "1.05");
1392 assert_eq!((a * b).to_string(), "2.205");
1393 assert_eq!(a.checked_div(b, 4).unwrap().to_string(), "0.5000");
1394 assert_eq!(
1396 decimal!(1).checked_div(decimal!(3), 5).unwrap().to_string(),
1397 "0.33333"
1398 );
1399 assert_eq!(
1400 decimal!(2).checked_div(decimal!(3), 5).unwrap().to_string(),
1401 "0.66667"
1402 );
1403 assert_eq!(decimal!(0.125).round_to(2).unwrap().to_string(), "0.12");
1404 assert_eq!(decimal!(0.135).round_to(2).unwrap().to_string(), "0.14");
1405 assert_eq!(Decimal::new(i64::MAX, 0).checked_add(Decimal::ONE), None);
1406 assert_eq!(decimal!(1).checked_div(Decimal::ZERO, 2), None);
1407 }
1408
1409 #[test]
1412 fn an_absurd_exponent_is_refused_rather_than_overflowing() {
1413 assert_eq!(decimal!(1.5).checked_pow10(i32::MIN), None);
1414 assert_eq!(decimal!(1.5).checked_pow10(i32::MAX), None);
1415 assert_eq!(Decimal::ZERO.checked_pow10(i32::MIN), Some(Decimal::ZERO));
1416 assert_eq!(decimal!(1).checked_pow10(19), None);
1417 assert_eq!(
1418 decimal!(1).checked_pow10(18).unwrap().mantissa(),
1419 10i64.pow(18)
1420 );
1421 }
1422
1423 #[test]
1424 fn a_change_of_unit_prefix_only_moves_the_point() {
1425 let kwh = decimal!(2935.600);
1427 assert_eq!(kwh.checked_pow10(3).unwrap().to_string(), "2935600");
1428 assert_eq!(kwh.checked_pow10(-3).unwrap().to_string(), "2.935600");
1429 assert_eq!(decimal!(1.5).checked_pow10(1).unwrap().to_string(), "15");
1430 }
1431
1432 #[test]
1433 fn comparison_is_numeric_and_ordering_is_total() {
1434 assert_eq!(decimal!(2.50), decimal!(2.5));
1435 assert!(decimal!(2.5) < decimal!(10));
1436 assert!(decimal!(-1) < Decimal::ZERO);
1437 assert_eq!(decimal!(1.10).min(decimal!(1.2)), decimal!(1.1));
1438 assert_eq!(decimal!(1.10).max(decimal!(1.2)), decimal!(1.2));
1439 assert_eq!(decimal!(2.500).normalized().to_string(), "2.5");
1440 }
1441
1442 #[test]
1446 fn every_serde_json_entry_point_agrees() {
1447 let value: Decimal = serde_json::from_str("1.230").unwrap();
1448 assert_eq!(serde_json::to_value(value).unwrap().to_string(), "1.23");
1449 let from_value: Decimal = serde_json::from_value(serde_json::json!(1.23)).unwrap();
1450 assert_eq!(from_value, decimal!(1.23));
1451 let from_int: Decimal = serde_json::from_value(serde_json::json!(7)).unwrap();
1452 assert_eq!(from_int, decimal!(7));
1453
1454 let mut de = serde_json::Deserializer::from_str("2935.600");
1456 let traced: Decimal = serde_path_to_error::deserialize(&mut de).unwrap();
1457 assert!(traced.eq_exact(decimal!(2935.600)));
1458 }
1459
1460 #[test]
1464 fn a_wrong_json_type_still_reads_as_a_type_error() {
1465 let error = serde_json::from_str::<Decimal>("\"42\"").unwrap_err();
1466 assert!(
1467 error.to_string().starts_with("invalid type: string"),
1468 "{error}"
1469 );
1470 assert_eq!(error.classify(), serde_json::error::Category::Data);
1471 for (text, expected) in [
1472 ("true", "invalid type: boolean"),
1473 ("null", "invalid type: null"),
1474 ("[]", "invalid type: sequence"),
1475 ("{}", "invalid type: map"),
1476 ] {
1477 let error = serde_json::from_str::<Decimal>(text).unwrap_err();
1478 assert!(error.to_string().starts_with(expected), "{text}: {error}");
1479 }
1480 }
1481
1482 #[test]
1483 fn floating_point_conversion_is_available_but_has_to_be_asked_for() {
1484 assert_eq!(Decimal::from_f64_lossy(0.1).unwrap(), decimal!(0.1));
1485 assert_eq!(
1486 Decimal::from_f64_lossy(1e18).unwrap().to_string(),
1487 "1000000000000000000"
1488 );
1489 assert_eq!(Decimal::from_f64_lossy(f64::NAN), None);
1490 assert_eq!(Decimal::from_f64_lossy(1e300), None);
1492 assert!((decimal!(2935.600).to_f64_lossy() - 2935.6).abs() < 1e-9);
1493 }
1494
1495 #[test]
1496 fn equal_values_hash_equally_whatever_their_scale() {
1497 use core::hash::BuildHasher;
1498 let state = std::collections::hash_map::RandomState::new();
1500 assert_eq!(
1501 state.hash_one(decimal!(2.50)),
1502 state.hash_one(decimal!(2.5))
1503 );
1504 assert_eq!(
1505 state.hash_one(Decimal::ZERO),
1506 state.hash_one(decimal!(0.000))
1507 );
1508 }
1509}