1use serde::{Deserialize, Serialize};
7use std::cmp::Ordering;
8use std::fmt;
9
10mod rounding;
11pub use rounding::parse_decimal_half_even;
12
13pub const SCALE: i128 = 1_000_000_000;
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
23pub struct ExactDecimal {
24 coefficient: i128,
25 scale: u8,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum DecimalRounding {
34 TowardZero,
35 AwayFromZero,
36 Floor,
37 Ceiling,
38 HalfEven,
39}
40
41#[derive(Deserialize)]
42#[serde(deny_unknown_fields)]
43struct ExactDecimalWire {
44 coefficient: String,
45 scale: u8,
46}
47
48impl Serialize for ExactDecimal {
49 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
50 where
51 S: serde::Serializer,
52 {
53 use serde::ser::SerializeStruct;
54
55 let mut value = serializer.serialize_struct("ExactDecimal", 2)?;
56 value.serialize_field("coefficient", &self.coefficient.to_string())?;
59 value.serialize_field("scale", &self.scale)?;
60 value.end()
61 }
62}
63
64impl<'de> Deserialize<'de> for ExactDecimal {
65 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
66 where
67 D: serde::Deserializer<'de>,
68 {
69 use serde::de::Error;
70
71 let wire = ExactDecimalWire::deserialize(deserializer)?;
72 let coefficient = wire
73 .coefficient
74 .parse::<i128>()
75 .map_err(|_| D::Error::custom("decimal coefficient is outside i128 range"))?;
76 let value = Self::from_parts(coefficient, wire.scale).map_err(D::Error::custom)?;
77 if value.coefficient != coefficient || value.scale != wire.scale {
78 return Err(D::Error::custom("decimal encoding must be normalized"));
79 }
80 Ok(value)
81 }
82}
83
84impl ExactDecimal {
85 pub const MAX_SCALE: u8 = 18;
86 pub const ZERO: Self = Self {
87 coefficient: 0,
88 scale: 0,
89 };
90 pub const ONE: Self = Self {
91 coefficient: 1,
92 scale: 0,
93 };
94
95 pub fn from_parts(coefficient: i128, scale: u8) -> Result<Self, &'static str> {
97 Self::normalized(coefficient, u32::from(scale))
98 }
99
100 pub const fn from_integer(coefficient: i128) -> Self {
102 if coefficient == 0 {
103 Self::ZERO
104 } else {
105 Self {
106 coefficient,
107 scale: 0,
108 }
109 }
110 }
111
112 pub fn from_legacy_raw(mut coefficient: i128) -> Self {
115 if coefficient == 0 {
116 return Self::ZERO;
117 }
118 let mut scale = 9;
119 while scale > 0 && coefficient % 10 == 0 {
120 coefficient /= 10;
121 scale -= 1;
122 }
123 Self { coefficient, scale }
124 }
125
126 fn normalized(mut coefficient: i128, mut scale: u32) -> Result<Self, &'static str> {
127 while scale > 0 && coefficient % 10 == 0 {
128 coefficient /= 10;
129 scale -= 1;
130 }
131 if scale > u32::from(Self::MAX_SCALE) {
132 return Err("decimal precision exceeds supported 18 places");
133 }
134 Ok(if coefficient == 0 {
135 Self::ZERO
136 } else {
137 Self {
138 coefficient,
139 scale: scale as u8,
140 }
141 })
142 }
143
144 pub fn parse(input: &str) -> Result<Self, &'static str> {
146 let value = input.trim();
147 if value.is_empty() {
148 return Err("empty decimal value");
149 }
150 let (negative, unsigned) = match value.strip_prefix('-') {
151 Some(rest) => (true, rest),
152 None => (false, value.strip_prefix('+').unwrap_or(value)),
153 };
154 let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
155 Some(index) => {
156 let exponent = unsigned[index + 1..]
157 .parse::<i32>()
158 .map_err(|_| "invalid decimal exponent")?;
159 (&unsigned[..index], exponent)
160 }
161 None => (unsigned, 0),
162 };
163 if !(-100..=100).contains(&exponent) {
164 return Err("decimal exponent is out of range");
165 }
166 let mut pieces = mantissa.split('.');
167 let whole = pieces.next().unwrap_or_default();
168 let fraction = pieces.next().unwrap_or_default();
169 if pieces.next().is_some()
170 || (whole.is_empty() && fraction.is_empty())
171 || !whole.bytes().all(|byte| byte.is_ascii_digit())
172 || !fraction.bytes().all(|byte| byte.is_ascii_digit())
173 {
174 return Err("invalid decimal value");
175 }
176 let magnitude = format!("{whole}{fraction}")
177 .parse::<u128>()
178 .map_err(|_| "decimal value is out of range")?;
179 if magnitude == 0 {
180 return Ok(Self::ZERO);
181 }
182
183 let mut scale = fraction.len() as i32 - exponent;
184 let magnitude = if scale < 0 {
185 let factor = 10_u128
186 .checked_pow((-scale) as u32)
187 .ok_or("decimal value is out of range")?;
188 scale = 0;
189 magnitude
190 .checked_mul(factor)
191 .ok_or("decimal value is out of range")?
192 } else {
193 magnitude
194 };
195 let mut magnitude = magnitude;
196 while scale > i32::from(Self::MAX_SCALE) && magnitude % 10 == 0 {
197 magnitude /= 10;
198 scale -= 1;
199 }
200 if scale > i32::from(Self::MAX_SCALE) {
201 return Err("decimal precision exceeds supported 18 places");
202 }
203
204 let signed = if negative {
205 let min_magnitude = (i128::MAX as u128) + 1;
206 if magnitude == min_magnitude {
207 i128::MIN
208 } else {
209 -i128::try_from(magnitude).map_err(|_| "decimal value is out of range")?
210 }
211 } else {
212 i128::try_from(magnitude).map_err(|_| "decimal value is out of range")?
213 };
214 Self::normalized(signed, scale as u32)
215 }
216
217 pub const fn coefficient(self) -> i128 {
218 self.coefficient
219 }
220
221 pub const fn scale(self) -> u8 {
222 self.scale
223 }
224
225 pub const fn is_zero(self) -> bool {
226 self.coefficient == 0
227 }
228
229 pub const fn is_positive(self) -> bool {
230 self.coefficient > 0
231 }
232
233 pub const fn is_negative(self) -> bool {
234 self.coefficient < 0
235 }
236
237 pub fn checked_neg(self) -> Option<Self> {
238 Some(Self {
239 coefficient: self.coefficient.checked_neg()?,
240 scale: self.scale,
241 })
242 }
243
244 pub fn checked_cmp(self, other: Self) -> Option<Ordering> {
246 let left_sign = self.coefficient.signum();
247 let right_sign = other.coefficient.signum();
248 match left_sign.cmp(&right_sign) {
249 Ordering::Equal if left_sign == 0 => Some(Ordering::Equal),
250 Ordering::Equal => {
251 let left = self.coefficient.unsigned_abs().to_string();
252 let right = other.coefficient.unsigned_abs().to_string();
253 let left_integer_digits = left.len() as i16 - i16::from(self.scale);
254 let right_integer_digits = right.len() as i16 - i16::from(other.scale);
255 let magnitude = left_integer_digits
256 .cmp(&right_integer_digits)
257 .then_with(|| {
258 let scale = self.scale.max(other.scale);
259 let left_aligned =
260 format!("{}{}", left, "0".repeat(usize::from(scale - self.scale)));
261 let right_aligned =
262 format!("{}{}", right, "0".repeat(usize::from(scale - other.scale)));
263 left_aligned.cmp(&right_aligned)
264 });
265 Some(if left_sign < 0 {
266 magnitude.reverse()
267 } else {
268 magnitude
269 })
270 }
271 ordering => Some(ordering),
272 }
273 }
274
275 pub fn to_raw(self, target_scale: u8) -> Result<i128, &'static str> {
277 if target_scale > Self::MAX_SCALE {
278 return Err("target decimal scale exceeds supported 18 places");
279 }
280 if target_scale >= self.scale {
281 let factor = 10_i128
282 .checked_pow(u32::from(target_scale - self.scale))
283 .ok_or("decimal value is out of range")?;
284 self.coefficient
285 .checked_mul(factor)
286 .ok_or("decimal value is out of range")
287 } else {
288 let divisor = 10_i128
289 .checked_pow(u32::from(self.scale - target_scale))
290 .ok_or("decimal value is out of range")?;
291 if self.coefficient % divisor != 0 {
292 return Err("decimal precision exceeds target scale");
293 }
294 Ok(self.coefficient / divisor)
295 }
296 }
297
298 pub fn to_raw_truncated(self, target_scale: u8) -> Result<i128, &'static str> {
303 if target_scale > Self::MAX_SCALE {
304 return Err("target decimal scale exceeds supported 18 places");
305 }
306 if target_scale >= self.scale {
307 return self.to_raw(target_scale);
308 }
309 let divisor = 10_i128
310 .checked_pow(u32::from(self.scale - target_scale))
311 .ok_or("decimal value is out of range")?;
312 Ok(self.coefficient / divisor)
313 }
314
315 pub fn checked_add(self, other: Self) -> Option<Self> {
316 self.checked_add_with_sign(other, false)
317 }
318
319 pub fn checked_sub(self, other: Self) -> Option<Self> {
320 self.checked_add_with_sign(other, true)
321 }
322
323 fn checked_add_with_sign(self, other: Self, subtract_other: bool) -> Option<Self> {
324 let scale = self.scale.max(other.scale);
325 let left = format!(
326 "{}{}",
327 self.coefficient.unsigned_abs(),
328 "0".repeat(usize::from(scale - self.scale))
329 );
330 let right = format!(
331 "{}{}",
332 other.coefficient.unsigned_abs(),
333 "0".repeat(usize::from(scale - other.scale))
334 );
335 let left_negative = self.coefficient < 0;
336 let right_negative = (other.coefficient < 0) ^ subtract_other;
337 let (digits, negative) = if left_negative == right_negative {
338 (add_unsigned_decimal_strings(&left, &right), left_negative)
339 } else {
340 match compare_unsigned_decimal_strings(&left, &right) {
341 Ordering::Greater => (
342 subtract_unsigned_decimal_strings(&left, &right),
343 left_negative,
344 ),
345 Ordering::Less => (
346 subtract_unsigned_decimal_strings(&right, &left),
347 right_negative,
348 ),
349 Ordering::Equal => return Some(Self::ZERO),
350 }
351 };
352 Self::from_signed_decimal_digits(digits, u32::from(scale), negative)
353 }
354
355 fn from_signed_decimal_digits(
356 mut digits: String,
357 mut scale: u32,
358 negative: bool,
359 ) -> Option<Self> {
360 let first_nonzero = digits.bytes().position(|byte| byte != b'0');
361 let Some(first_nonzero) = first_nonzero else {
362 return Some(Self::ZERO);
363 };
364 if first_nonzero > 0 {
365 digits.drain(..first_nonzero);
366 }
367 while scale > 0 && digits.ends_with('0') {
368 digits.pop();
369 scale -= 1;
370 }
371 if scale > u32::from(Self::MAX_SCALE) {
372 return None;
373 }
374 let magnitude = digits.parse::<u128>().ok()?;
375 let coefficient = if negative {
376 let min_magnitude = (i128::MAX as u128) + 1;
377 if magnitude == min_magnitude {
378 i128::MIN
379 } else {
380 -i128::try_from(magnitude).ok()?
381 }
382 } else {
383 i128::try_from(magnitude).ok()?
384 };
385 Some(Self {
386 coefficient,
387 scale: scale as u8,
388 })
389 }
390
391 pub fn checked_mul(self, other: Self) -> Option<Self> {
392 let mut digits = multiply_unsigned_decimal_strings(
393 &self.coefficient.unsigned_abs().to_string(),
394 &other.coefficient.unsigned_abs().to_string(),
395 );
396 let mut scale = u32::from(self.scale) + u32::from(other.scale);
397 while scale > 0 && digits.ends_with('0') {
398 digits.pop();
399 scale -= 1;
400 }
401 if scale > u32::from(Self::MAX_SCALE) {
402 return None;
403 }
404 let magnitude = digits.parse::<u128>().ok()?;
405 let negative = (self.coefficient < 0) != (other.coefficient < 0);
406 let coefficient = if negative {
407 let min_magnitude = (i128::MAX as u128) + 1;
408 if magnitude == min_magnitude {
409 i128::MIN
410 } else {
411 -i128::try_from(magnitude).ok()?
412 }
413 } else {
414 i128::try_from(magnitude).ok()?
415 };
416 Some(Self {
417 coefficient,
418 scale: scale as u8,
419 })
420 }
421
422 pub fn checked_mul_at_scale(
425 self,
426 other: Self,
427 target_scale: u8,
428 rounding: DecimalRounding,
429 ) -> Option<Self> {
430 if target_scale > Self::MAX_SCALE {
431 return None;
432 }
433 let negative = (self.coefficient < 0) != (other.coefficient < 0);
434 let mut digits = multiply_unsigned_decimal_strings(
435 &self.coefficient.unsigned_abs().to_string(),
436 &other.coefficient.unsigned_abs().to_string(),
437 );
438 let product_scale = u16::from(self.scale) + u16::from(other.scale);
439 let target = u16::from(target_scale);
440 if product_scale < target {
441 digits.push_str(&"0".repeat(usize::from(target - product_scale)));
442 } else if product_scale > target {
443 let divisor = format!("1{}", "0".repeat(usize::from(product_scale - target)));
444 let (quotient, remainder) = divide_unsigned_decimal_strings(&digits, &divisor)?;
445 let round_up = should_round_up("ient, &remainder, &divisor, negative, rounding)?;
446 digits = if round_up {
447 add_unsigned_decimal_strings("ient, "1")
448 } else {
449 quotient
450 };
451 }
452 Self::from_signed_decimal_digits(digits, u32::from(target_scale), negative)
453 }
454
455 pub fn checked_div_at_scale(
459 self,
460 other: Self,
461 target_scale: u8,
462 rounding: DecimalRounding,
463 ) -> Option<Self> {
464 if other.coefficient == 0 || target_scale > Self::MAX_SCALE {
465 return None;
466 }
467 let negative = (self.coefficient < 0) != (other.coefficient < 0);
468 let mut numerator = self.coefficient.unsigned_abs().to_string();
469 let mut denominator = other.coefficient.unsigned_abs().to_string();
470 let shift = i16::from(target_scale) + i16::from(other.scale) - i16::from(self.scale);
471 if shift >= 0 {
472 numerator.push_str(&"0".repeat(shift as usize));
473 } else {
474 denominator.push_str(&"0".repeat((-shift) as usize));
475 }
476 let (mut quotient, remainder) = divide_unsigned_decimal_strings(&numerator, &denominator)?;
477 if should_round_up("ient, &remainder, &denominator, negative, rounding)? {
478 quotient = add_unsigned_decimal_strings("ient, "1");
479 }
480 Self::from_signed_decimal_digits(quotient, u32::from(target_scale), negative)
481 }
482
483 pub fn is_multiple_of(self, step: Self) -> Option<bool> {
485 if !step.is_positive() {
486 return None;
487 }
488 let mut numerator = self.coefficient.unsigned_abs().to_string();
489 let mut denominator = step.coefficient.unsigned_abs().to_string();
490 let shift = i16::from(step.scale) - i16::from(self.scale);
491 if shift >= 0 {
492 numerator.push_str(&"0".repeat(shift as usize));
493 } else {
494 denominator.push_str(&"0".repeat((-shift) as usize));
495 }
496 let (_, remainder) = divide_unsigned_decimal_strings(&numerator, &denominator)?;
497 Some(remainder == "0")
498 }
499}
500
501fn should_round_up(
502 quotient: &str,
503 remainder: &str,
504 denominator: &str,
505 negative: bool,
506 rounding: DecimalRounding,
507) -> Option<bool> {
508 if remainder == "0" {
509 return Some(false);
510 }
511 Some(match rounding {
512 DecimalRounding::TowardZero => false,
513 DecimalRounding::AwayFromZero => true,
514 DecimalRounding::Floor => negative,
515 DecimalRounding::Ceiling => !negative,
516 DecimalRounding::HalfEven => {
517 let doubled_remainder = add_unsigned_decimal_strings(remainder, remainder);
518 match compare_unsigned_decimal_strings(&doubled_remainder, denominator) {
519 Ordering::Greater => true,
520 Ordering::Less => false,
521 Ordering::Equal => quotient
522 .as_bytes()
523 .last()
524 .is_some_and(|digit| (digit - b'0') % 2 == 1),
525 }
526 }
527 })
528}
529
530fn divide_unsigned_decimal_strings(numerator: &str, denominator: &str) -> Option<(String, String)> {
533 let numerator = numerator.trim_start_matches('0');
534 let denominator = denominator.trim_start_matches('0');
535 if denominator.is_empty() {
536 return None;
537 }
538 if numerator.is_empty() {
539 return Some(("0".into(), "0".into()));
540 }
541
542 let mut quotient = String::with_capacity(numerator.len());
543 let mut remainder = String::from("0");
544 for digit in numerator.bytes() {
545 if remainder == "0" {
546 remainder.clear();
547 }
548 remainder.push(char::from(digit));
549 let trimmed = remainder.trim_start_matches('0');
550 remainder = if trimmed.is_empty() {
551 String::from("0")
552 } else {
553 trimmed.to_string()
554 };
555 let mut quotient_digit = 0_u8;
556 while quotient_digit < 9 {
557 let next = multiply_unsigned_decimal_string_by_digit(denominator, quotient_digit + 1);
558 if compare_unsigned_decimal_strings(&next, &remainder) == Ordering::Greater {
559 break;
560 }
561 quotient_digit += 1;
562 }
563 if quotient_digit > 0 {
564 let product = multiply_unsigned_decimal_string_by_digit(denominator, quotient_digit);
565 remainder = subtract_unsigned_decimal_strings(&remainder, &product);
566 }
567 quotient.push(char::from(b'0' + quotient_digit));
568 }
569 let quotient = quotient.trim_start_matches('0');
570 Some((
571 if quotient.is_empty() { "0" } else { quotient }.into(),
572 remainder,
573 ))
574}
575
576fn multiply_unsigned_decimal_string_by_digit(value: &str, digit: u8) -> String {
577 if digit == 0 || value == "0" {
578 return String::from("0");
579 }
580 let mut output = Vec::with_capacity(value.len() + 1);
581 let mut carry = 0_u16;
582 for byte in value.bytes().rev() {
583 let product = u16::from(byte - b'0') * u16::from(digit) + carry;
584 output.push((product % 10) as u8);
585 carry = product / 10;
586 }
587 while carry > 0 {
588 output.push((carry % 10) as u8);
589 carry /= 10;
590 }
591 output
592 .iter()
593 .rev()
594 .map(|value| char::from(b'0' + *value))
595 .collect()
596}
597
598fn multiply_unsigned_decimal_strings(left: &str, right: &str) -> String {
604 let left = left
605 .bytes()
606 .rev()
607 .map(|byte| u32::from(byte - b'0'))
608 .collect::<Vec<_>>();
609 let right = right
610 .bytes()
611 .rev()
612 .map(|byte| u32::from(byte - b'0'))
613 .collect::<Vec<_>>();
614 let mut product = vec![0_u32; left.len() + right.len()];
615 for (left_index, left_digit) in left.iter().copied().enumerate() {
616 for (right_index, right_digit) in right.iter().copied().enumerate() {
617 product[left_index + right_index] += left_digit * right_digit;
618 }
619 }
620 for index in 0..product.len() - 1 {
621 let carry = product[index] / 10;
622 product[index] %= 10;
623 product[index + 1] += carry;
624 }
625 while product.len() > 1 && product.last() == Some(&0) {
626 product.pop();
627 }
628 product
629 .iter()
630 .rev()
631 .map(|digit| char::from(b'0' + *digit as u8))
632 .collect()
633}
634
635fn compare_unsigned_decimal_strings(left: &str, right: &str) -> Ordering {
636 let left = left.trim_start_matches('0');
637 let right = right.trim_start_matches('0');
638 left.len().cmp(&right.len()).then_with(|| left.cmp(right))
639}
640
641fn add_unsigned_decimal_strings(left: &str, right: &str) -> String {
642 let left = left
643 .bytes()
644 .rev()
645 .map(|byte| byte - b'0')
646 .collect::<Vec<_>>();
647 let right = right
648 .bytes()
649 .rev()
650 .map(|byte| byte - b'0')
651 .collect::<Vec<_>>();
652 let mut result = Vec::with_capacity(left.len().max(right.len()) + 1);
653 let mut carry = 0_u8;
654 for index in 0..left.len().max(right.len()) {
655 let sum =
656 left.get(index).copied().unwrap_or(0) + right.get(index).copied().unwrap_or(0) + carry;
657 result.push(sum % 10);
658 carry = sum / 10;
659 }
660 if carry > 0 {
661 result.push(carry);
662 }
663 result
664 .iter()
665 .rev()
666 .map(|digit| char::from(b'0' + *digit))
667 .collect()
668}
669
670fn subtract_unsigned_decimal_strings(left: &str, right: &str) -> String {
672 let left = left
673 .bytes()
674 .rev()
675 .map(|byte| byte - b'0')
676 .collect::<Vec<_>>();
677 let right = right
678 .bytes()
679 .rev()
680 .map(|byte| byte - b'0')
681 .collect::<Vec<_>>();
682 let mut result = Vec::with_capacity(left.len());
683 let mut borrow = 0_i16;
684 for (index, left_digit) in left.iter().copied().enumerate() {
685 let mut difference =
686 i16::from(left_digit) - borrow - i16::from(right.get(index).copied().unwrap_or(0));
687 if difference < 0 {
688 difference += 10;
689 borrow = 1;
690 } else {
691 borrow = 0;
692 }
693 result.push(difference as u8);
694 }
695 while result.len() > 1 && result.last() == Some(&0) {
696 result.pop();
697 }
698 result
699 .iter()
700 .rev()
701 .map(|digit| char::from(b'0' + *digit))
702 .collect()
703}
704
705impl fmt::Display for ExactDecimal {
706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 if self.scale == 0 {
708 return write!(f, "{}", self.coefficient);
709 }
710 let negative = self.coefficient < 0;
711 let magnitude = self.coefficient.unsigned_abs();
712 let divisor = 10_u128.pow(u32::from(self.scale));
713 let whole = magnitude / divisor;
714 let fraction = magnitude % divisor;
715 let mut digits = format!("{fraction:0width$}", width = usize::from(self.scale));
716 while digits.ends_with('0') {
717 digits.pop();
718 }
719 write!(f, "{}{}.{}", if negative { "-" } else { "" }, whole, digits)
720 }
721}
722
723pub fn parse_decimal_exact(input: &str) -> Result<i128, &'static str> {
729 ExactDecimal::parse(input)
730 .and_then(|decimal| decimal.to_raw(9))
731 .map_err(|error| match error {
732 "decimal precision exceeds supported 18 places"
733 | "decimal precision exceeds target scale" => "decimal precision exceeds 1e-9",
734 other => other,
735 })
736}
737
738pub fn parse_decimal_scaled_integer(input: &str, multiplier: i64) -> Result<i64, &'static str> {
743 if multiplier <= 0 {
744 return Err("decimal multiplier must be positive");
745 }
746 let raw = parse_decimal_exact(input)?;
747 let scaled = raw
748 .checked_mul(i128::from(multiplier))
749 .ok_or("scaled decimal value is out of range")?;
750 if scaled % SCALE != 0 {
751 return Err("decimal value exceeds integer unit precision");
752 }
753 i64::try_from(scaled / SCALE).map_err(|_| "scaled decimal value is out of range")
754}
755
756pub fn parse_decimal_integer_exact(input: &str) -> Result<i128, &'static str> {
758 let value = input.trim();
759 if value.is_empty() {
760 return Err("empty decimal value");
761 }
762 let (negative, unsigned) = match value.strip_prefix('-') {
763 Some(rest) => (true, rest),
764 None => (false, value.strip_prefix('+').unwrap_or(value)),
765 };
766 let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
767 Some(index) => {
768 let exponent = unsigned[index + 1..]
769 .parse::<i32>()
770 .map_err(|_| "invalid decimal exponent")?;
771 (&unsigned[..index], exponent)
772 }
773 None => (unsigned, 0),
774 };
775 if !(-100..=100).contains(&exponent) {
776 return Err("decimal exponent is out of range");
777 }
778 let mut pieces = mantissa.split('.');
779 let whole = pieces.next().unwrap_or_default();
780 let fraction = pieces.next().unwrap_or_default();
781 if pieces.next().is_some()
782 || (whole.is_empty() && fraction.is_empty())
783 || !whole.bytes().all(|byte| byte.is_ascii_digit())
784 || !fraction.bytes().all(|byte| byte.is_ascii_digit())
785 {
786 return Err("invalid decimal value");
787 }
788 let magnitude = format!("{whole}{fraction}")
789 .parse::<u128>()
790 .map_err(|_| "decimal value is out of range")?;
791 let power = exponent - fraction.len() as i32;
792 let integer = if power >= 0 {
793 magnitude
794 .checked_mul(
795 10_u128
796 .checked_pow(power as u32)
797 .ok_or("decimal value is out of range")?,
798 )
799 .ok_or("decimal value is out of range")?
800 } else {
801 let places = (-power) as u32;
802 if places > 38 {
803 if magnitude == 0 {
804 0
805 } else {
806 return Err("decimal value is not an integer");
807 }
808 } else {
809 let divisor = 10_u128.pow(places);
810 if magnitude % divisor != 0 {
811 return Err("decimal value is not an integer");
812 }
813 magnitude / divisor
814 }
815 };
816 if negative {
817 let min_magnitude = (i128::MAX as u128) + 1;
818 if integer == min_magnitude {
819 Ok(i128::MIN)
820 } else {
821 i128::try_from(integer)
822 .map(|value| -value)
823 .map_err(|_| "decimal value is out of range")
824 }
825 } else {
826 i128::try_from(integer).map_err(|_| "decimal value is out of range")
827 }
828}
829
830pub(crate) fn parse_dec(s: &str) -> Option<i128> {
832 let s = s.trim();
833 let (neg, body) = match s.strip_prefix('-') {
834 Some(b) => (true, b),
835 None => (false, s),
836 };
837 let mut it = body.split('.');
838 let int_part = it.next()?;
839 let frac_part = it.next().unwrap_or("");
840 if it.next().is_some() {
841 return None;
842 }
843 if int_part.is_empty() && frac_part.is_empty() {
844 return None;
845 }
846 if !int_part.chars().all(|c| c.is_ascii_digit()) {
847 return None;
848 }
849 if !frac_part.chars().all(|c| c.is_ascii_digit()) {
850 return None;
851 }
852 if frac_part.len() > 9 {
853 return None;
854 }
855 let mut v: i128 = if int_part.is_empty() {
856 0
857 } else {
858 int_part.parse().ok()?
859 };
860 v = v.checked_mul(SCALE)?;
861 if !frac_part.is_empty() {
862 let mut f: i128 = frac_part.parse().ok()?;
863 for _ in frac_part.len()..9 {
864 f *= 10;
865 }
866 v = v.checked_add(f)?;
867 }
868 Some(if neg { -v } else { v })
869}
870
871fn fmt_dec(raw: i128, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872 let neg = raw < 0;
873 let raw = raw.unsigned_abs();
874 let scale = SCALE as u128;
875 let int = raw / scale;
876 let frac = raw % scale;
877 let mut s = format!("{:09}", frac);
878 while s.ends_with('0') {
879 s.pop();
880 }
881 let sign = if neg { "-" } else { "" };
882 if s.is_empty() {
883 write!(f, "{}{}", sign, int)
884 } else {
885 write!(f, "{}{}.{}", sign, int, s)
886 }
887}
888
889macro_rules! impl_fixed {
890 ($name:ident, $doc:expr) => {
891 #[doc = $doc]
892 #[derive(
893 Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
894 )]
895 pub struct $name(pub i128);
896
897 impl $name {
898 pub const ZERO: Self = Self(0);
899
900 pub const fn from_raw(raw: i128) -> Self {
901 Self(raw)
902 }
903
904 pub const fn raw(self) -> i128 {
905 self.0
906 }
907
908 pub fn from_i64(v: i64) -> Self {
909 Self(v as i128 * SCALE)
910 }
911
912 pub fn from_dec(s: &str) -> Option<Self> {
914 parse_dec(s).map(Self)
915 }
916
917 pub fn checked_add(self, o: Self) -> Option<Self> {
918 self.0.checked_add(o.0).map(Self)
919 }
920
921 pub fn checked_sub(self, o: Self) -> Option<Self> {
922 self.0.checked_sub(o.0).map(Self)
923 }
924
925 pub fn checked_mul(self, o: Self) -> Option<Self> {
927 self.0.checked_mul(o.0).map(|v| Self(v / SCALE))
928 }
929
930 pub fn checked_div(self, o: Self) -> Option<Self> {
932 if o.0 == 0 {
933 return None;
934 }
935 self.0.checked_mul(SCALE).map(|v| Self(v / o.0))
936 }
937
938 pub fn is_zero(self) -> bool {
939 self.0 == 0
940 }
941
942 pub fn checked_abs(self) -> Option<Self> {
943 self.0.checked_abs().map(Self)
944 }
945
946 pub fn abs(self) -> Self {
949 Self(self.0.saturating_abs())
950 }
951 }
952
953 impl fmt::Debug for $name {
954 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
955 fmt_dec(self.0, f)
956 }
957 }
958
959 impl fmt::Display for $name {
960 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
961 fmt_dec(self.0, f)
962 }
963 }
964 };
965}
966
967impl_fixed!(Fixed, "通用定点数(9 位小数)");
968impl_fixed!(Price, "价格");
969impl_fixed!(Quantity, "数量");
970impl_fixed!(Money, "金额");
971
972#[cfg(test)]
973mod tests {
974 use super::*;
975
976 #[test]
977 fn parse_and_display_roundtrip() {
978 let p = Price::from_dec("123.45").unwrap();
979 assert_eq!(p.raw(), 123_450_000_000);
980 assert_eq!(format!("{}", p), "123.45");
981 }
982
983 #[test]
984 fn exact_decimal_preserves_precision_beyond_legacy_scale() {
985 let amount = ExactDecimal::parse("0.000000000123456789").unwrap();
986 assert_eq!(amount.coefficient(), 123_456_789);
987 assert_eq!(amount.scale(), 18);
988 assert_eq!(amount.to_string(), "0.000000000123456789");
989 assert_eq!(amount.to_raw(18), Ok(123_456_789));
990 assert_eq!(
991 amount.to_raw(9),
992 Err("decimal precision exceeds target scale")
993 );
994 assert_eq!(
995 parse_decimal_exact("0.000000000123456789"),
996 Err("decimal precision exceeds 1e-9")
997 );
998 assert_eq!(amount.to_raw_truncated(9), Ok(0));
999 assert_eq!(
1000 ExactDecimal::parse("-0.0000000019")
1001 .unwrap()
1002 .to_raw_truncated(9),
1003 Ok(-1)
1004 );
1005 }
1006
1007 #[test]
1008 fn exact_decimal_normalizes_exponents_and_trailing_zeroes() {
1009 let one = ExactDecimal::parse("1000e-3").unwrap();
1010 assert_eq!(one, ExactDecimal::parse("1.0000").unwrap());
1011 assert_eq!(one.scale(), 0);
1012 assert_eq!(one.to_string(), "1");
1013
1014 let subnano = ExactDecimal::parse("1.234567890000000000e-9").unwrap();
1015 assert_eq!(subnano.to_string(), "0.00000000123456789");
1016 assert_eq!(
1017 ExactDecimal::parse("1.0000000000000000000")
1018 .unwrap()
1019 .to_string(),
1020 "1"
1021 );
1022 }
1023
1024 #[test]
1025 fn exact_decimal_arithmetic_aligns_scales_without_rounding() {
1026 let left = ExactDecimal::parse("0.0000000001").unwrap();
1027 let right = ExactDecimal::parse("0.00000000002").unwrap();
1028 assert_eq!(
1029 left.checked_add(right).unwrap().to_string(),
1030 "0.00000000012"
1031 );
1032 assert_eq!(
1033 left.checked_sub(right).unwrap().to_string(),
1034 "0.00000000008"
1035 );
1036 assert_eq!(
1037 ExactDecimal::parse("0.00000001")
1038 .unwrap()
1039 .checked_mul(ExactDecimal::parse("0.00000002").unwrap())
1040 .unwrap()
1041 .to_string(),
1042 "0.0000000000000002"
1043 );
1044 }
1045
1046 #[test]
1047 fn exact_decimal_scaled_division_applies_explicit_signed_rounding() {
1048 let one = ExactDecimal::parse("1").unwrap();
1049 let three = ExactDecimal::parse("3").unwrap();
1050 let third = one
1051 .checked_div_at_scale(three, 4, DecimalRounding::TowardZero)
1052 .unwrap();
1053 assert_eq!(third.to_string(), "0.3333");
1054 assert_eq!(
1055 one.checked_div_at_scale(three, 4, DecimalRounding::AwayFromZero)
1056 .unwrap()
1057 .to_string(),
1058 "0.3334"
1059 );
1060 assert_eq!(
1061 one.checked_div_at_scale(three, 4, DecimalRounding::Ceiling)
1062 .unwrap()
1063 .to_string(),
1064 "0.3334"
1065 );
1066 assert_eq!(
1067 one.checked_div_at_scale(three, 4, DecimalRounding::Floor)
1068 .unwrap()
1069 .to_string(),
1070 "0.3333"
1071 );
1072
1073 let negative_one = ExactDecimal::parse("-1").unwrap();
1074 assert_eq!(
1075 negative_one
1076 .checked_div_at_scale(three, 4, DecimalRounding::Floor)
1077 .unwrap()
1078 .to_string(),
1079 "-0.3334"
1080 );
1081 assert_eq!(
1082 negative_one
1083 .checked_div_at_scale(three, 4, DecimalRounding::Ceiling)
1084 .unwrap()
1085 .to_string(),
1086 "-0.3333"
1087 );
1088 }
1089
1090 #[test]
1091 fn exact_decimal_scaled_multiplication_and_half_even_are_deterministic() {
1092 let first = ExactDecimal::parse("1.245").unwrap();
1093 let second = ExactDecimal::parse("1.255").unwrap();
1094 assert_eq!(
1095 first
1096 .checked_mul_at_scale(
1097 ExactDecimal::parse("1").unwrap(),
1098 2,
1099 DecimalRounding::HalfEven,
1100 )
1101 .unwrap()
1102 .to_string(),
1103 "1.24"
1104 );
1105 assert_eq!(
1106 second
1107 .checked_mul_at_scale(
1108 ExactDecimal::parse("1").unwrap(),
1109 2,
1110 DecimalRounding::HalfEven,
1111 )
1112 .unwrap()
1113 .to_string(),
1114 "1.26"
1115 );
1116 assert_eq!(
1117 ExactDecimal::parse("0.0000000001")
1118 .unwrap()
1119 .checked_mul_at_scale(
1120 ExactDecimal::parse("0.1").unwrap(),
1121 10,
1122 DecimalRounding::AwayFromZero,
1123 )
1124 .unwrap()
1125 .to_string(),
1126 "0.0000000001"
1127 );
1128 }
1129
1130 #[test]
1131 fn exact_decimal_checks_exchange_steps_without_rescaling_to_nine_places() {
1132 let step = ExactDecimal::parse("0.0000000001").unwrap();
1133 assert_eq!(
1134 ExactDecimal::parse("0.0000000003")
1135 .unwrap()
1136 .is_multiple_of(step),
1137 Some(true)
1138 );
1139 assert_eq!(
1140 ExactDecimal::parse("0.00000000031")
1141 .unwrap()
1142 .is_multiple_of(step),
1143 Some(false)
1144 );
1145 assert_eq!(
1146 ExactDecimal::parse("1")
1147 .unwrap()
1148 .is_multiple_of(ExactDecimal::ZERO),
1149 None
1150 );
1151 }
1152
1153 #[test]
1154 fn exact_decimal_multiplication_normalizes_before_checking_i128_overflow() {
1155 let value = ExactDecimal::from_parts(i128::MAX, 18).unwrap();
1156 let ten = ExactDecimal::from_parts(10, 0).unwrap();
1157 assert_eq!(
1158 value.checked_mul(ten),
1159 Some(ExactDecimal::from_parts(i128::MAX, 17).unwrap())
1160 );
1161
1162 let negative_min = ExactDecimal::from_parts(i128::MIN, 18).unwrap();
1163 assert_eq!(
1164 negative_min.checked_mul(ten),
1165 Some(ExactDecimal::from_parts(i128::MIN, 17).unwrap())
1166 );
1167
1168 assert_eq!(
1169 ExactDecimal::parse("0.00000001")
1170 .unwrap()
1171 .checked_mul(ExactDecimal::parse("0.00000002").unwrap())
1172 .unwrap()
1173 .to_string(),
1174 "0.0000000000000002"
1175 );
1176 }
1177
1178 #[test]
1179 fn exact_decimal_addition_normalizes_wide_intermediates_and_handles_i128_min() {
1180 let left = ExactDecimal::from_parts(i128::MAX, 18).unwrap();
1181 let right = ExactDecimal::from_parts(i128::MAX - 4, 18).unwrap();
1182 assert_eq!(
1183 left.checked_add(right),
1184 Some(ExactDecimal::parse("340282366920938463463.37460743176821145").unwrap())
1185 );
1186
1187 let minimum = ExactDecimal::from_parts(i128::MIN, 0).unwrap();
1188 let minus_one = ExactDecimal::from_parts(-1, 0).unwrap();
1189 assert_eq!(
1190 minimum.checked_sub(minus_one),
1191 Some(ExactDecimal::from_parts(i128::MIN + 1, 0).unwrap())
1192 );
1193 assert_eq!(
1194 minimum.checked_add(ExactDecimal::from_parts(i128::MAX, 0).unwrap()),
1195 Some(ExactDecimal::from_parts(-1, 0).unwrap())
1196 );
1197 }
1198
1199 #[test]
1200 fn exact_decimal_json_roundtrip_validates_scale() {
1201 let value = ExactDecimal::parse("-0.000000000123456789").unwrap();
1202 let json = serde_json::to_string(&value).unwrap();
1203 assert!(json.contains(r#""coefficient":"-123456789""#));
1204 assert_eq!(serde_json::from_str::<ExactDecimal>(&json).unwrap(), value);
1205 assert!(serde_json::from_str::<ExactDecimal>(r#"{"coefficient":"1","scale":19}"#).is_err());
1206 assert!(serde_json::from_str::<ExactDecimal>(r#"{"coefficient":"10","scale":1}"#).is_err());
1207 }
1208
1209 #[test]
1210 fn json_i128_raw_values_roundtrip_without_float_conversion() {
1211 #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
1212 struct RawAmount {
1213 qty_raw: i128,
1214 }
1215
1216 let samples = [
1217 u64::MAX as i128,
1218 u64::MAX as i128 + 1,
1219 100_000_000_000_000_000_001_i128,
1220 i128::MAX,
1221 i128::MIN,
1222 ];
1223 for qty_raw in samples {
1224 let expected = RawAmount { qty_raw };
1225 let json = serde_json::to_string(&expected).unwrap();
1226 assert_eq!(json, format!(r#"{{"qty_raw":{qty_raw}}}"#));
1227 assert_eq!(serde_json::from_str::<RawAmount>(&json).unwrap(), expected);
1228
1229 let value: serde_json::Value = serde_json::from_str(&json).unwrap();
1230 assert_eq!(value["qty_raw"].to_string(), qty_raw.to_string());
1231 assert_eq!(
1232 serde_json::from_value::<RawAmount>(value).unwrap(),
1233 expected
1234 );
1235 }
1236 }
1237
1238 #[test]
1239 fn negative_value() {
1240 let m = Money::from_dec("-0.000000001").unwrap();
1241 assert_eq!(m.raw(), -1);
1242 assert_eq!(format!("{}", m), "-0.000000001");
1243 }
1244
1245 #[test]
1246 fn fixed_point_mul_div() {
1247 let a = Price::from_dec("2.5").unwrap();
1248 let b = Quantity::from_dec("4").unwrap();
1249 let notional = Money::from_raw(
1250 Fixed::from_raw(a.raw())
1251 .checked_mul(Fixed::from_raw(b.raw()))
1252 .unwrap()
1253 .raw(),
1254 );
1255 assert_eq!(format!("{}", notional), "10");
1256 }
1257
1258 #[test]
1259 fn rejects_over_precision() {
1260 assert!(Price::from_dec("1.1234567891").is_none());
1261 }
1262
1263 #[test]
1264 fn exact_decimal_parser_accepts_exponents_and_rejects_rounding() {
1265 assert_eq!(parse_decimal_exact(" +1.25e2 "), Ok(125 * SCALE));
1266 assert_eq!(parse_decimal_exact("1.23e-2"), Ok(12_300_000));
1267 assert_eq!(parse_decimal_exact("-0.000000001"), Ok(-1));
1268 assert_eq!(parse_decimal_exact("1.0000000000"), Ok(SCALE));
1269 assert_eq!(
1270 parse_decimal_exact("1.0000000001"),
1271 Err("decimal precision exceeds 1e-9")
1272 );
1273 }
1274
1275 #[test]
1276 fn exact_decimal_parser_checks_sign_syntax_and_i128_bounds() {
1277 assert_eq!(parse_decimal_exact(""), Err("empty decimal value"));
1278 assert_eq!(parse_decimal_exact("NaN"), Err("invalid decimal value"));
1279 assert_eq!(
1280 parse_decimal_exact("1e101"),
1281 Err("decimal exponent is out of range")
1282 );
1283 assert_eq!(
1284 parse_decimal_exact("170141183460469231731687303715.884105727"),
1285 Ok(i128::MAX)
1286 );
1287 assert_eq!(
1288 parse_decimal_exact("-170141183460469231731687303715.884105728"),
1289 Ok(i128::MIN)
1290 );
1291 assert_eq!(
1292 parse_decimal_exact("170141183460469231731687303715.884105728"),
1293 Err("decimal value is out of range")
1294 );
1295 }
1296
1297 #[test]
1298 fn decimal_to_integer_units_preserves_exact_basis_point_semantics() {
1299 assert_eq!(parse_decimal_scaled_integer("0.005", 10_000), Ok(50));
1300 assert_eq!(parse_decimal_scaled_integer("0.5", 100), Ok(50));
1301 assert_eq!(parse_decimal_scaled_integer("-0.0001", 10_000), Ok(-1));
1302 assert_eq!(
1303 parse_decimal_scaled_integer("0.00001", 10_000),
1304 Err("decimal value exceeds integer unit precision")
1305 );
1306 assert_eq!(
1307 parse_decimal_scaled_integer("1", 0),
1308 Err("decimal multiplier must be positive")
1309 );
1310 }
1311
1312 #[test]
1313 fn exact_integer_parser_rejects_fraction_and_preserves_i128_range() {
1314 assert_eq!(parse_decimal_integer_exact("1.0"), Ok(1));
1315 assert_eq!(parse_decimal_integer_exact("1e3"), Ok(1_000));
1316 assert_eq!(
1317 parse_decimal_integer_exact("1.1"),
1318 Err("decimal value is not an integer")
1319 );
1320 assert_eq!(
1321 parse_decimal_integer_exact("170141183460469231731687303715884105727"),
1322 Ok(i128::MAX)
1323 );
1324 }
1325
1326 #[test]
1327 fn extreme_absolute_value_is_checked_without_panicking() {
1328 let value = Fixed::from_raw(i128::MIN);
1329 assert!(value.checked_abs().is_none());
1330 assert_eq!(value.abs().raw(), i128::MAX);
1331 assert!(format!("{}", value).starts_with('-'));
1332 }
1333
1334 #[test]
1335 fn legacy_raw_constructor_matches_the_checked_scale_nine_constructor() {
1336 for raw in [
1337 i128::MIN,
1338 -10_000_000_000,
1339 -1,
1340 0,
1341 1,
1342 10_000_000_000,
1343 i128::MAX,
1344 ] {
1345 let legacy = ExactDecimal::from_legacy_raw(raw);
1346 assert!(ExactDecimal::from_parts(raw, 9).is_ok_and(|checked| checked == legacy));
1347 }
1348 assert_eq!(ExactDecimal::from_integer(0), ExactDecimal::ZERO);
1349 assert_eq!(ExactDecimal::from_integer(12).coefficient(), 12);
1350 }
1351}