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]
314 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
315 let scale = if self.scale > rhs.scale {
316 self.scale
317 } else {
318 rhs.scale
319 };
320 let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
321 return None;
322 };
323 narrow(a + b, scale)
324 }
325
326 #[must_use]
331 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
332 let scale = if self.scale > rhs.scale {
333 self.scale
334 } else {
335 rhs.scale
336 };
337 let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
338 return None;
339 };
340 narrow(a - b, scale)
341 }
342
343 #[must_use]
345 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
346 let scale = self.scale as u32 + rhs.scale as u32;
347 let product = self.mantissa as i128 * rhs.mantissa as i128;
348 if scale <= Self::MAX_SCALE as u32 {
349 return narrow(product, scale as u8);
350 }
351 let drop = scale - Self::MAX_SCALE as u32;
353 let negative = product < 0;
354 let rounded = round_off(product.unsigned_abs(), drop, false);
355 if rounded > i64::MAX as u128 {
356 return None;
357 }
358 let mantissa = rounded as i64;
359 Some(Self {
360 mantissa: if negative { -mantissa } else { mantissa },
361 scale: Self::MAX_SCALE,
362 })
363 }
364
365 #[must_use]
371 pub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self> {
372 if rhs.mantissa == 0 || scale > Self::MAX_SCALE {
373 return None;
374 }
375 let shift = scale as i32 + rhs.scale as i32 - self.scale as i32;
377 let negative = (self.mantissa < 0) != (rhs.mantissa < 0);
378 let mut numerator = self.mantissa.unsigned_abs() as u128;
379 let denominator = rhs.mantissa.unsigned_abs() as u128;
380 let shift = shift + 1;
382 let mut extra_drop = 0u32;
383 if shift >= 0 {
384 let up = shift as u32;
385 if up > 38 {
386 return None;
387 }
388 let factor = pow10_i128(up) as u128;
389 let Some(scaled) = numerator.checked_mul(factor) else {
390 return None;
391 };
392 numerator = scaled;
393 } else {
394 let down = (-shift) as u32;
397 if down > 38 {
398 return None;
399 }
400 extra_drop = down;
401 }
402 let quotient = if extra_drop > 0 {
403 let factor = pow10_i128(extra_drop) as u128;
404 let Some(scaled) = denominator.checked_mul(factor) else {
405 return None;
406 };
407 numerator / scaled
408 } else {
409 numerator / denominator
410 };
411 let remainder_is_zero = if extra_drop > 0 {
412 let factor = pow10_i128(extra_drop) as u128;
413 match denominator.checked_mul(factor) {
414 Some(scaled) => numerator.is_multiple_of(scaled),
415 None => return None,
416 }
417 } else {
418 numerator.is_multiple_of(denominator)
419 };
420 let rounded = round_off(quotient, 1, !remainder_is_zero);
421 if rounded > i64::MAX as u128 {
422 return None;
423 }
424 let mantissa = rounded as i64;
425 Some(Self {
426 mantissa: if negative { -mantissa } else { mantissa },
427 scale,
428 })
429 }
430
431 #[must_use]
438 pub const fn checked_pow10(self, exp: i32) -> Option<Self> {
439 if exp == 0 {
440 return Some(self);
441 }
442 if exp > 40 || exp < -40 {
446 return if self.mantissa == 0 {
447 Some(Self::ZERO)
448 } else {
449 None
450 };
451 }
452 if exp < 0 {
453 let want = self.scale as i32 - exp;
455 if want <= Self::MAX_SCALE as i32 {
456 return Some(Self {
457 mantissa: self.mantissa,
458 scale: want as u8,
459 });
460 }
461 let surplus = want - Self::MAX_SCALE as i32;
463 let surplus = surplus as u32;
464 if surplus > 18 {
465 return None;
466 }
467 let factor = POW10_U64[surplus as usize] as i64;
468 if self.mantissa % factor != 0 {
469 return None;
470 }
471 return Some(Self {
472 mantissa: self.mantissa / factor,
473 scale: Self::MAX_SCALE,
474 });
475 }
476 let mut left = exp as u32;
478 let mut mantissa = self.mantissa;
479 let mut scale = self.scale;
480 while left > 0 && scale > 0 {
481 scale -= 1;
482 left -= 1;
483 }
484 while left > 0 {
485 let step = if left > 18 { 18 } else { left };
486 let Some(next) = mantissa.checked_mul(POW10_U64[step as usize] as i64) else {
487 return None;
488 };
489 mantissa = next;
490 left -= step;
491 }
492 Some(Self { mantissa, scale })
493 }
494
495 #[must_use]
497 pub const fn checked_abs(self) -> Option<Self> {
498 let Some(mantissa) = self.mantissa.checked_abs() else {
499 return None;
500 };
501 Some(Self {
502 mantissa,
503 scale: self.scale,
504 })
505 }
506
507 #[must_use]
509 pub const fn checked_neg(self) -> Option<Self> {
510 let Some(mantissa) = self.mantissa.checked_neg() else {
511 return None;
512 };
513 Some(Self {
514 mantissa,
515 scale: self.scale,
516 })
517 }
518
519 #[must_use]
521 pub const fn min(self, other: Self) -> Self {
522 match self.compare(other) {
523 Ordering::Greater => other,
524 _ => self,
525 }
526 }
527
528 #[must_use]
530 pub const fn max(self, other: Self) -> Self {
531 match self.compare(other) {
532 Ordering::Less => other,
533 _ => self,
534 }
535 }
536
537 #[must_use]
539 pub const fn compare(self, other: Self) -> Ordering {
540 let scale = if self.scale > other.scale {
541 self.scale
542 } else {
543 other.scale
544 };
545 match (self.to_i128_at(scale), other.to_i128_at(scale)) {
546 (Some(a), Some(b)) => {
547 if a < b {
548 Ordering::Less
549 } else if a > b {
550 Ordering::Greater
551 } else {
552 Ordering::Equal
553 }
554 }
555 _ => {
558 if self.mantissa < other.mantissa {
559 Ordering::Less
560 } else if self.mantissa > other.mantissa {
561 Ordering::Greater
562 } else {
563 Ordering::Equal
564 }
565 }
566 }
567 }
568
569 const fn to_i128_at(self, scale: u8) -> Option<i128> {
571 if scale < self.scale {
572 return None;
573 }
574 let factor = pow10_i128((scale - self.scale) as u32);
575 Some(self.mantissa as i128 * factor)
576 }
577
578 #[allow(clippy::too_many_lines)]
598 pub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError> {
599 let n = bytes.len();
600 let mut i = 0usize;
601 while i < n && is_space(bytes[i]) {
602 i += 1;
603 }
604 let mut negative = false;
605 if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
606 negative = bytes[i] == b'-';
607 i += 1;
608 }
609
610 let mut magnitude: u128 = 0;
611 let mut fraction_digits: i64 = 0;
612 let mut skipped_integer_digits: i64 = 0;
613 let mut round_digit: u8 = 0;
614 let mut sticky = false;
615 let mut dropped_any = false;
616 let mut seen_digit = false;
617 let mut seen_point = false;
618
619 while i < n {
620 let byte = bytes[i];
621 if byte == b'.' {
622 if seen_point {
623 return Err(ParseDecimalError::Invalid);
624 }
625 seen_point = true;
626 i += 1;
627 continue;
628 }
629 if byte < b'0' || byte > b'9' {
630 break;
631 }
632 seen_digit = true;
633 let digit = byte - b'0';
634 if magnitude < ACCUMULATE_LIMIT {
635 magnitude = magnitude * 10 + digit as u128;
636 if seen_point {
637 fraction_digits += 1;
638 }
639 } else {
640 if !seen_point {
642 skipped_integer_digits += 1;
643 }
644 if dropped_any {
645 if digit != 0 {
646 sticky = true;
647 }
648 } else {
649 round_digit = digit;
650 dropped_any = true;
651 }
652 }
653 i += 1;
654 }
655 if !seen_digit {
656 return Err(ParseDecimalError::Invalid);
657 }
658 let mut rounded_off = false;
659 if dropped_any {
660 if round_digit > 5 || (round_digit == 5 && (sticky || magnitude % 2 == 1)) {
661 magnitude += 1;
662 }
663 rounded_off = true;
664 }
665
666 let mut exponent: i64 = 0;
667 if i < n && (bytes[i] == b'e' || bytes[i] == b'E') {
668 i += 1;
669 let mut exponent_negative = false;
670 if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
671 exponent_negative = bytes[i] == b'-';
672 i += 1;
673 }
674 let mut seen_exponent_digit = false;
675 while i < n && bytes[i] >= b'0' && bytes[i] <= b'9' {
676 seen_exponent_digit = true;
677 if exponent < 1_000_000 {
679 exponent = exponent * 10 + (bytes[i] - b'0') as i64;
680 }
681 i += 1;
682 }
683 if !seen_exponent_digit {
684 return Err(ParseDecimalError::Invalid);
685 }
686 if exponent_negative {
687 exponent = -exponent;
688 }
689 }
690 while i < n && is_space(bytes[i]) {
691 i += 1;
692 }
693 if i != n {
694 return Err(ParseDecimalError::Invalid);
695 }
696
697 let mut scale = fraction_digits - skipped_integer_digits - exponent;
699 if magnitude == 0 {
700 if scale < 0 || scale > Self::MAX_SCALE as i64 {
703 scale = 0;
704 }
705 return Ok(Self {
706 mantissa: 0,
707 scale: scale as u8,
708 });
709 }
710
711 if scale < 0 {
712 let shift = -scale;
713 if shift > 38 {
714 return Err(ParseDecimalError::Overflow);
715 }
716 let factor = pow10_i128(shift as u32) as u128;
717 let Some(scaled) = magnitude.checked_mul(factor) else {
718 return Err(ParseDecimalError::Overflow);
719 };
720 magnitude = scaled;
721 scale = 0;
722 } else if scale > Self::MAX_SCALE as i64 {
723 let drop = scale - Self::MAX_SCALE as i64;
724 if drop > 39 {
725 magnitude = 0;
726 } else {
727 let dropped = drop as u32;
728 magnitude = round_off(magnitude, dropped, false);
729 }
730 scale = Self::MAX_SCALE as i64;
731 rounded_off = true;
732 }
733
734 while magnitude > i64::MAX as u128 {
736 if scale == 0 {
737 return Err(ParseDecimalError::Overflow);
738 }
739 magnitude = round_off(magnitude, 1, false);
740 scale -= 1;
741 rounded_off = true;
742 }
743 let _ = rounded_off;
744 let mantissa = magnitude as i64;
745 Ok(Self {
746 mantissa: if negative { -mantissa } else { mantissa },
747 scale: scale as u8,
748 })
749 }
750
751 #[must_use]
763 pub const fn from_literal(text: &str) -> Self {
764 let bytes = text.as_bytes();
765 let mut digits = [0u8; 64];
767 let mut len = 0usize;
768 let mut i = 0usize;
769 while i < bytes.len() {
770 if bytes[i] != b'_' {
771 assert!(len < 64, "decimal literal is too long");
772 digits[len] = bytes[i];
773 len += 1;
774 }
775 i += 1;
776 }
777 let (kept, _) = digits.split_at(len);
778 match Self::from_ascii(kept) {
779 Ok(value) => value,
780 Err(ParseDecimalError::Invalid) => panic!("not a decimal number"),
781 Err(ParseDecimalError::Overflow) => panic!("decimal number out of range"),
782 }
783 }
784
785 #[must_use]
793 #[allow(clippy::cast_precision_loss)] pub fn to_f64_lossy(self) -> f64 {
795 const POW10_F64: [f64; 19] = [
796 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
797 1e16, 1e17, 1e18,
798 ];
799 let mantissa = self.mantissa as f64;
800 mantissa / POW10_F64[self.scale as usize]
801 }
802
803 #[must_use]
811 pub fn from_f64_lossy(value: f64) -> Option<Self> {
812 if !value.is_finite() {
813 return None;
814 }
815 let mut buffer = TextBuffer::new();
816 if fmt::Write::write_fmt(&mut buffer, format_args!("{value:e}")).is_err() {
819 return None;
820 }
821 Self::from_ascii(buffer.as_bytes()).ok()
822 }
823}
824
825const fn round_off(magnitude: u128, digits: u32, sticky: bool) -> u128 {
830 if digits == 0 {
831 return magnitude;
832 }
833 if digits > 38 {
834 return 0;
835 }
836 let divisor = pow10_i128(digits) as u128;
837 let quotient = magnitude / divisor;
838 let remainder = magnitude % divisor;
839 let half = divisor / 2;
840 if remainder > half || (remainder == half && (sticky || quotient % 2 == 1)) {
841 quotient + 1
842 } else {
843 quotient
844 }
845}
846
847const fn narrow(mantissa: i128, scale: u8) -> Option<Decimal> {
849 if mantissa > i64::MAX as i128 || mantissa < i64::MIN as i128 {
850 return None;
851 }
852 Some(Decimal {
853 mantissa: mantissa as i64,
854 scale,
855 })
856}
857
858const fn is_space(byte: u8) -> bool {
859 matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
860}
861
862#[derive(Clone, Copy, Debug, PartialEq, Eq)]
864#[non_exhaustive]
865pub enum ParseDecimalError {
866 Invalid,
868 Overflow,
870}
871
872impl fmt::Display for ParseDecimalError {
873 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
874 f.write_str(match self {
875 ParseDecimalError::Invalid => "not a decimal number",
876 ParseDecimalError::Overflow => "decimal number out of range",
877 })
878 }
879}
880
881#[cfg(feature = "std")]
882impl std::error::Error for ParseDecimalError {}
883
884impl FromStr for Decimal {
885 type Err = ParseDecimalError;
886
887 fn from_str(text: &str) -> Result<Self, Self::Err> {
888 Self::from_ascii(text.as_bytes())
889 }
890}
891
892impl fmt::Debug for Decimal {
893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896 write!(f, "Decimal({self})")
897 }
898}
899
900impl fmt::Display for Decimal {
901 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 if self.scale == 0 {
904 return write!(f, "{}", self.mantissa);
905 }
906 let magnitude = self.mantissa.unsigned_abs();
907 let divisor = POW10_U64[self.scale as usize];
908 let sign = if self.mantissa < 0 { "-" } else { "" };
909 write!(
910 f,
911 "{sign}{}.{:0width$}",
912 magnitude / divisor,
913 magnitude % divisor,
914 width = self.scale as usize
915 )
916 }
917}
918
919impl PartialEq for Decimal {
924 fn eq(&self, other: &Self) -> bool {
925 self.compare(*other) == Ordering::Equal
926 }
927}
928
929impl Eq for Decimal {}
930
931impl PartialOrd for Decimal {
932 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
933 Some(self.cmp(other))
934 }
935}
936
937impl Ord for Decimal {
938 fn cmp(&self, other: &Self) -> Ordering {
939 self.compare(*other)
940 }
941}
942
943impl Hash for Decimal {
944 fn hash<H: Hasher>(&self, state: &mut H) {
946 let normalized = self.normalized();
947 normalized.mantissa.hash(state);
948 normalized.scale.hash(state);
949 }
950}
951
952macro_rules! binary_op {
957 ($trait:ident, $method:ident, $checked:ident, $what:literal) => {
958 impl $trait for Decimal {
959 type Output = Decimal;
960 fn $method(self, rhs: Decimal) -> Decimal {
964 self.$checked(rhs)
965 .expect(concat!("Decimal ", $what, " overflowed"))
966 }
967 }
968 };
969}
970
971binary_op!(Add, add, checked_add, "addition");
972binary_op!(Sub, sub, checked_sub, "subtraction");
973binary_op!(Mul, mul, checked_mul, "multiplication");
974
975impl Div for Decimal {
976 type Output = Decimal;
977
978 fn div(self, rhs: Decimal) -> Decimal {
985 self.checked_div(rhs, Decimal::MAX_SCALE)
986 .expect("Decimal division by zero or overflow")
987 }
988}
989
990impl Neg for Decimal {
991 type Output = Decimal;
992
993 fn neg(self) -> Decimal {
997 self.checked_neg().expect("Decimal negation overflowed")
998 }
999}
1000
1001impl AddAssign for Decimal {
1002 fn add_assign(&mut self, rhs: Decimal) {
1003 *self = *self + rhs;
1004 }
1005}
1006
1007impl SubAssign for Decimal {
1008 fn sub_assign(&mut self, rhs: Decimal) {
1009 *self = *self - rhs;
1010 }
1011}
1012
1013impl core::iter::Sum for Decimal {
1014 fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
1015 iter.fold(Decimal::ZERO, |total, value| total + value)
1016 }
1017}
1018
1019macro_rules! from_integer {
1024 ($($ty:ty),*) => {
1025 $(
1026 impl From<$ty> for Decimal {
1027 fn from(value: $ty) -> Self {
1028 Self { mantissa: i64::from(value), scale: 0 }
1029 }
1030 }
1031 )*
1032 };
1033}
1034
1035from_integer!(i8, i16, i32, i64, u8, u16, u32);
1036
1037impl TryFrom<u64> for Decimal {
1038 type Error = ParseDecimalError;
1039
1040 fn try_from(value: u64) -> Result<Self, Self::Error> {
1041 i64::try_from(value)
1042 .map(Self::from_i64)
1043 .map_err(|_| ParseDecimalError::Overflow)
1044 }
1045}
1046
1047impl TryFrom<Decimal> for i64 {
1048 type Error = ParseDecimalError;
1049
1050 fn try_from(value: Decimal) -> Result<Self, Self::Error> {
1052 value
1053 .rescale(0)
1054 .map(Decimal::mantissa)
1055 .ok_or(ParseDecimalError::Invalid)
1056 }
1057}
1058
1059const TEXT_CAPACITY: usize = 40;
1065
1066struct TextBuffer {
1067 bytes: [u8; TEXT_CAPACITY],
1068 len: usize,
1069}
1070
1071impl TextBuffer {
1072 const fn new() -> Self {
1073 Self {
1074 bytes: [0; TEXT_CAPACITY],
1075 len: 0,
1076 }
1077 }
1078
1079 fn as_bytes(&self) -> &[u8] {
1080 &self.bytes[..self.len]
1081 }
1082
1083 fn as_str(&self) -> &str {
1084 core::str::from_utf8(self.as_bytes()).unwrap_or("0")
1087 }
1088}
1089
1090impl fmt::Write for TextBuffer {
1091 fn write_str(&mut self, text: &str) -> fmt::Result {
1092 let end = self.len + text.len();
1093 if end > TEXT_CAPACITY {
1094 return Err(fmt::Error);
1095 }
1096 self.bytes[self.len..end].copy_from_slice(text.as_bytes());
1097 self.len = end;
1098 Ok(())
1099 }
1100}
1101
1102const RAW_TOKEN: &str = "$serde_json::private::RawValue";
1113
1114impl Serialize for Decimal {
1115 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1118 use serde::ser::SerializeStruct as _;
1119 let mut buffer = TextBuffer::new();
1120 if fmt::Write::write_fmt(&mut buffer, format_args!("{self}")).is_err() {
1121 return Err(serde::ser::Error::custom("decimal is too long to render"));
1122 }
1123 let mut raw = serializer.serialize_struct(RAW_TOKEN, 1)?;
1124 raw.serialize_field(RAW_TOKEN, buffer.as_str())?;
1125 raw.end()
1126 }
1127}
1128
1129impl<'de> Deserialize<'de> for Decimal {
1130 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1131 deserializer.deserialize_newtype_struct(RAW_TOKEN, DecimalVisitor)
1132 }
1133}
1134
1135struct DecimalVisitor;
1136
1137impl<'de> serde::de::Visitor<'de> for DecimalVisitor {
1138 type Value = Decimal;
1139
1140 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1141 f.write_str("a JSON number")
1142 }
1143
1144 fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Decimal, E> {
1145 Ok(Decimal::from_i64(value))
1146 }
1147
1148 fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Decimal, E> {
1149 Decimal::try_from(value).map_err(|_| E::custom("number out of range for a decimal"))
1150 }
1151
1152 fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Decimal, E> {
1153 Decimal::from_f64_lossy(value)
1154 .ok_or_else(|| E::custom("number is not a finite decimal in range"))
1155 }
1156
1157 fn visit_newtype_struct<D: serde::Deserializer<'de>>(
1160 self,
1161 deserializer: D,
1162 ) -> Result<Decimal, D::Error> {
1163 deserializer.deserialize_any(DecimalVisitor)
1164 }
1165
1166 fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Decimal, A::Error> {
1169 use serde::de::Error as _;
1170 let Some(RawKey) = map.next_key::<RawKey>()? else {
1171 return Err(A::Error::custom("expected a JSON number"));
1172 };
1173 let RawToken(value) = map.next_value::<RawToken>()?;
1174 Ok(value)
1175 }
1176}
1177
1178struct RawKey;
1180
1181impl<'de> Deserialize<'de> for RawKey {
1182 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1183 struct KeyVisitor;
1184 impl serde::de::Visitor<'_> for KeyVisitor {
1185 type Value = RawKey;
1186 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187 f.write_str("a raw value marker")
1188 }
1189 fn visit_str<E: serde::de::Error>(self, _value: &str) -> Result<RawKey, E> {
1190 Ok(RawKey)
1191 }
1192 }
1193 deserializer.deserialize_identifier(KeyVisitor)
1194 }
1195}
1196
1197struct RawToken(Decimal);
1199
1200impl<'de> Deserialize<'de> for RawToken {
1201 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1202 struct TokenVisitor;
1203 impl serde::de::Visitor<'_> for TokenVisitor {
1204 type Value = RawToken;
1205
1206 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1207 f.write_str("a JSON number")
1208 }
1209
1210 fn visit_str<E: serde::de::Error>(self, token: &str) -> Result<RawToken, E> {
1211 use serde::de::Unexpected;
1212 let trimmed = token.trim();
1217 let unexpected = match trimmed.as_bytes().first() {
1218 Some(b'"') => Some(Unexpected::Str(trimmed.trim_matches('"'))),
1219 Some(b'{') => Some(Unexpected::Map),
1220 Some(b'[') => Some(Unexpected::Seq),
1221 Some(b't') => Some(Unexpected::Bool(true)),
1222 Some(b'f') => Some(Unexpected::Bool(false)),
1223 Some(b'n') => Some(Unexpected::Unit),
1224 _ => None,
1225 };
1226 if let Some(unexpected) = unexpected {
1227 return Err(E::invalid_type(unexpected, &"a JSON number"));
1228 }
1229 Decimal::from_ascii(trimmed.as_bytes())
1230 .map(RawToken)
1231 .map_err(|error| {
1232 let expected: &str = match error {
1233 ParseDecimalError::Overflow => "a decimal number in range",
1234 ParseDecimalError::Invalid => "a decimal number",
1235 };
1236 E::invalid_value(Unexpected::Other(trimmed), &expected)
1237 })
1238 }
1239 }
1240 deserializer.deserialize_str(TokenVisitor)
1241 }
1242}
1243
1244impl Validate for Decimal {
1245 fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
1248}
1249
1250#[macro_export]
1267macro_rules! decimal {
1268 ($($token:tt)+) => {
1269 const {
1270 $crate::types::Decimal::from_literal(::core::stringify!($($token)+))
1271 }
1272 };
1273}
1274
1275#[cfg(test)]
1276mod tests {
1277 use super::*;
1278 use alloc::string::ToString;
1279
1280 #[test]
1281 fn the_scale_the_station_sent_survives_the_round_trip() {
1282 let value: Decimal = serde_json::from_str("2935.600").unwrap();
1285 assert_eq!(value.scale(), 3);
1286 assert_eq!(value.mantissa(), 2_935_600);
1287 assert_eq!(serde_json::to_string(&value).unwrap(), "2935.600");
1288 assert_eq!(value.to_string(), "2935.600");
1289
1290 let short: Decimal = serde_json::from_str("2935.6").unwrap();
1292 assert_eq!(value, short);
1293 assert!(!value.eq_exact(short));
1294 }
1295
1296 #[test]
1297 fn a_difference_of_two_registers_is_exact() {
1298 let start: Decimal = "0.1".parse().unwrap();
1300 let stop: Decimal = "10.2".parse().unwrap();
1301 assert_eq!((stop - start).to_string(), "10.1");
1302 }
1303
1304 #[test]
1305 fn every_json_number_spelling_parses() {
1306 for (text, expected) in [
1307 ("0", "0"),
1308 ("-0", "0"),
1309 ("42", "42"),
1310 ("-17.25", "-17.25"),
1311 ("0.00", "0.00"),
1312 ("1e3", "1000"),
1313 ("1.5E+3", "1500"),
1314 ("15e-1", "1.5"),
1315 ("2E-4", "0.0002"),
1316 ("0.000000000000000001", "0.000000000000000001"),
1317 ("9223372036854775807", "9223372036854775807"),
1318 ] {
1319 let value: Decimal = text.parse().unwrap_or_else(|_| panic!("{text}"));
1320 assert_eq!(value.to_string(), expected, "{text}");
1321 }
1322 for text in ["", "-", "abc", "1.2.3", "1e", "NaN", "1 2", "--1"] {
1323 assert!(text.parse::<Decimal>().is_err(), "{text} should not parse");
1324 }
1325 }
1326
1327 #[test]
1328 fn excess_precision_rounds_half_to_even_rather_than_failing() {
1329 let value: Decimal = "0.12345678901234567895".parse().unwrap();
1331 assert_eq!(value.scale(), Decimal::MAX_SCALE);
1332 assert_eq!(value.to_string(), "0.123456789012345679");
1333 assert_eq!("1e30".parse::<Decimal>(), Err(ParseDecimalError::Overflow));
1335 }
1336
1337 #[test]
1338 fn arithmetic_is_exact_and_checked() {
1339 let a = decimal!(1.05);
1340 let b = decimal!(2.1);
1341 assert_eq!((a + b).to_string(), "3.15");
1342 assert_eq!((b - a).to_string(), "1.05");
1343 assert_eq!((a * b).to_string(), "2.205");
1344 assert_eq!(a.checked_div(b, 4).unwrap().to_string(), "0.5000");
1345 assert_eq!(
1347 decimal!(1).checked_div(decimal!(3), 5).unwrap().to_string(),
1348 "0.33333"
1349 );
1350 assert_eq!(
1351 decimal!(2).checked_div(decimal!(3), 5).unwrap().to_string(),
1352 "0.66667"
1353 );
1354 assert_eq!(decimal!(0.125).round_to(2).unwrap().to_string(), "0.12");
1355 assert_eq!(decimal!(0.135).round_to(2).unwrap().to_string(), "0.14");
1356 assert_eq!(Decimal::new(i64::MAX, 0).checked_add(Decimal::ONE), None);
1357 assert_eq!(decimal!(1).checked_div(Decimal::ZERO, 2), None);
1358 }
1359
1360 #[test]
1363 fn an_absurd_exponent_is_refused_rather_than_overflowing() {
1364 assert_eq!(decimal!(1.5).checked_pow10(i32::MIN), None);
1365 assert_eq!(decimal!(1.5).checked_pow10(i32::MAX), None);
1366 assert_eq!(Decimal::ZERO.checked_pow10(i32::MIN), Some(Decimal::ZERO));
1367 assert_eq!(decimal!(1).checked_pow10(19), None);
1368 assert_eq!(
1369 decimal!(1).checked_pow10(18).unwrap().mantissa(),
1370 10i64.pow(18)
1371 );
1372 }
1373
1374 #[test]
1375 fn a_change_of_unit_prefix_only_moves_the_point() {
1376 let kwh = decimal!(2935.600);
1378 assert_eq!(kwh.checked_pow10(3).unwrap().to_string(), "2935600");
1379 assert_eq!(kwh.checked_pow10(-3).unwrap().to_string(), "2.935600");
1380 assert_eq!(decimal!(1.5).checked_pow10(1).unwrap().to_string(), "15");
1381 }
1382
1383 #[test]
1384 fn comparison_is_numeric_and_ordering_is_total() {
1385 assert_eq!(decimal!(2.50), decimal!(2.5));
1386 assert!(decimal!(2.5) < decimal!(10));
1387 assert!(decimal!(-1) < Decimal::ZERO);
1388 assert_eq!(decimal!(1.10).min(decimal!(1.2)), decimal!(1.1));
1389 assert_eq!(decimal!(1.10).max(decimal!(1.2)), decimal!(1.2));
1390 assert_eq!(decimal!(2.500).normalized().to_string(), "2.5");
1391 }
1392
1393 #[test]
1397 fn every_serde_json_entry_point_agrees() {
1398 let value: Decimal = serde_json::from_str("1.230").unwrap();
1399 assert_eq!(serde_json::to_value(value).unwrap().to_string(), "1.23");
1400 let from_value: Decimal = serde_json::from_value(serde_json::json!(1.23)).unwrap();
1401 assert_eq!(from_value, decimal!(1.23));
1402 let from_int: Decimal = serde_json::from_value(serde_json::json!(7)).unwrap();
1403 assert_eq!(from_int, decimal!(7));
1404
1405 let mut de = serde_json::Deserializer::from_str("2935.600");
1407 let traced: Decimal = serde_path_to_error::deserialize(&mut de).unwrap();
1408 assert!(traced.eq_exact(decimal!(2935.600)));
1409 }
1410
1411 #[test]
1415 fn a_wrong_json_type_still_reads_as_a_type_error() {
1416 let error = serde_json::from_str::<Decimal>("\"42\"").unwrap_err();
1417 assert!(
1418 error.to_string().starts_with("invalid type: string"),
1419 "{error}"
1420 );
1421 assert_eq!(error.classify(), serde_json::error::Category::Data);
1422 for (text, expected) in [
1423 ("true", "invalid type: boolean"),
1424 ("null", "invalid type: null"),
1425 ("[]", "invalid type: sequence"),
1426 ("{}", "invalid type: map"),
1427 ] {
1428 let error = serde_json::from_str::<Decimal>(text).unwrap_err();
1429 assert!(error.to_string().starts_with(expected), "{text}: {error}");
1430 }
1431 }
1432
1433 #[test]
1434 fn floating_point_conversion_is_available_but_has_to_be_asked_for() {
1435 assert_eq!(Decimal::from_f64_lossy(0.1).unwrap(), decimal!(0.1));
1436 assert_eq!(
1437 Decimal::from_f64_lossy(1e18).unwrap().to_string(),
1438 "1000000000000000000"
1439 );
1440 assert_eq!(Decimal::from_f64_lossy(f64::NAN), None);
1441 assert_eq!(Decimal::from_f64_lossy(1e300), None);
1443 assert!((decimal!(2935.600).to_f64_lossy() - 2935.6).abs() < 1e-9);
1444 }
1445
1446 #[test]
1447 fn equal_values_hash_equally_whatever_their_scale() {
1448 use core::hash::BuildHasher;
1449 let state = std::collections::hash_map::RandomState::new();
1451 assert_eq!(
1452 state.hash_one(decimal!(2.50)),
1453 state.hash_one(decimal!(2.5))
1454 );
1455 assert_eq!(
1456 state.hash_one(Decimal::ZERO),
1457 state.hash_one(decimal!(0.000))
1458 );
1459 }
1460}