1#[derive(Debug, Clone, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum BigNumberError {
39 InvalidFormat(String),
41 ExponentOutOfRange(String),
43}
44
45impl std::fmt::Display for BigNumberError {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 match self {
48 BigNumberError::InvalidFormat(s) => write!(f, "invalid number format: {s}"),
49 BigNumberError::ExponentOutOfRange(s) => {
50 write!(f, "number exponent is outside the supported range: {s}")
51 }
52 }
53 }
54}
55
56impl std::error::Error for BigNumberError {}
57
58fn is_ascii_digits(s: &str) -> bool {
60 !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
61}
62
63fn is_valid_big_integer(s: &str) -> bool {
71 is_ascii_digits(s.strip_prefix('-').unwrap_or(s))
72}
73
74fn validate_big_decimal(s: &str) -> Result<(), BigNumberError> {
85 let invalid_format = || BigNumberError::InvalidFormat(s.to_string());
86 let exponent_out_of_range = || BigNumberError::ExponentOutOfRange(s.to_string());
87
88 let (coefficient, exponent) = match s.split_once(['e', 'E']) {
89 Some((coefficient, exponent)) => match exponent.parse::<i128>() {
90 Ok(exponent) => (coefficient, exponent),
91 Err(error)
92 if matches!(
93 error.kind(),
94 std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow
95 ) =>
96 {
97 return Err(exponent_out_of_range());
98 }
99 Err(_) => return Err(invalid_format()),
100 },
101 None => (s, 0),
102 };
103
104 let coefficient = coefficient.strip_prefix(['-', '+']).unwrap_or(coefficient);
105 let (integer, fraction) = coefficient.split_once('.').unwrap_or((coefficient, ""));
106
107 if (integer.is_empty() && fraction.is_empty())
108 || !integer
109 .bytes()
110 .chain(fraction.bytes())
111 .all(|byte| byte.is_ascii_digit())
112 {
113 return Err(invalid_format());
114 }
115
116 match (fraction.len() as i128).checked_sub(exponent) {
117 Some(scale) if (-(i64::MAX as i128)..=i64::MAX as i128).contains(&scale) => Ok(()),
118 _ => Err(exponent_out_of_range()),
119 }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Hash)]
129#[cfg_attr(
130 all(aws_sdk_unstable, feature = "serde-serialize"),
131 derive(serde::Serialize)
132)]
133pub struct BigInteger(String);
134
135#[cfg(all(aws_sdk_unstable, feature = "serde-deserialize"))]
136impl<'de> serde::Deserialize<'de> for BigInteger {
137 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
138 where
139 D: serde::Deserializer<'de>,
140 {
141 let value = <String as serde::Deserialize>::deserialize(deserializer)?;
142 value.parse().map_err(serde::de::Error::custom)
143 }
144}
145
146impl Default for BigInteger {
147 fn default() -> Self {
148 Self("0".to_string())
149 }
150}
151
152impl std::str::FromStr for BigInteger {
153 type Err = BigNumberError;
154
155 fn from_str(s: &str) -> Result<Self, Self::Err> {
156 if !is_valid_big_integer(s) {
157 return Err(BigNumberError::InvalidFormat(s.to_string()));
158 }
159 Ok(Self(s.to_string()))
160 }
161}
162
163impl AsRef<str> for BigInteger {
164 fn as_ref(&self) -> &str {
165 &self.0
166 }
167}
168
169#[derive(Debug, Clone)]
180#[cfg_attr(
181 all(aws_sdk_unstable, feature = "serde-serialize"),
182 derive(serde::Serialize)
183)]
184pub struct BigDecimal(String);
185
186struct Canonical<'a> {
193 negative: bool,
194 integer: &'a str,
195 fraction: &'a str,
196 exponent: i128,
197}
198
199impl<'a> Canonical<'a> {
200 fn of(s: &'a str) -> Self {
203 let (coefficient, exponent) = match s.split_once(['e', 'E']) {
204 Some((coefficient, exponent)) => (
205 coefficient,
206 exponent.parse::<i128>().expect("validated when parsed"),
207 ),
208 None => (s, 0),
209 };
210 let negative = coefficient.starts_with('-');
211 let coefficient = coefficient.strip_prefix(['-', '+']).unwrap_or(coefficient);
212 let (integer, fraction) = coefficient.split_once('.').unwrap_or((coefficient, ""));
213
214 let mut exponent = exponent - fraction.len() as i128;
216
217 let mut fraction_kept = fraction.trim_end_matches('0');
220 exponent += (fraction.len() - fraction_kept.len()) as i128;
221 let mut integer_kept = integer;
222 if fraction_kept.is_empty() {
223 integer_kept = integer.trim_end_matches('0');
224 exponent += (integer.len() - integer_kept.len()) as i128;
225 }
226
227 integer_kept = integer_kept.trim_start_matches('0');
230 if integer_kept.is_empty() {
231 fraction_kept = fraction_kept.trim_start_matches('0');
232 }
233
234 if integer_kept.is_empty() && fraction_kept.is_empty() {
235 return Self {
236 negative: false,
237 integer: "",
238 fraction: "",
239 exponent: 0,
240 };
241 }
242 Self {
243 negative,
244 integer: integer_kept,
245 fraction: fraction_kept,
246 exponent,
247 }
248 }
249
250 fn digits(&self) -> impl Iterator<Item = u8> + 'a {
251 self.integer.bytes().chain(self.fraction.bytes())
252 }
253}
254
255impl PartialEq for BigDecimal {
256 fn eq(&self, other: &Self) -> bool {
257 let (a, b) = (Canonical::of(&self.0), Canonical::of(&other.0));
258 a.negative == b.negative && a.exponent == b.exponent && a.digits().eq(b.digits())
259 }
260}
261
262impl Eq for BigDecimal {}
263
264impl std::hash::Hash for BigDecimal {
265 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
266 let canonical = Canonical::of(&self.0);
267 canonical.negative.hash(state);
268 canonical.exponent.hash(state);
269 let mut count = 0usize;
273 for digit in canonical.digits() {
274 state.write_u8(digit);
275 count += 1;
276 }
277 state.write_usize(count);
278 }
279}
280
281#[cfg(all(aws_sdk_unstable, feature = "serde-deserialize"))]
282impl<'de> serde::Deserialize<'de> for BigDecimal {
283 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
284 where
285 D: serde::Deserializer<'de>,
286 {
287 let value = <String as serde::Deserialize>::deserialize(deserializer)?;
288 value.parse().map_err(serde::de::Error::custom)
289 }
290}
291
292impl Default for BigDecimal {
293 fn default() -> Self {
294 Self("0.0".to_string())
295 }
296}
297
298impl std::str::FromStr for BigDecimal {
299 type Err = BigNumberError;
300
301 fn from_str(s: &str) -> Result<Self, Self::Err> {
302 validate_big_decimal(s)?;
303 Ok(Self(s.to_string()))
304 }
305}
306
307impl AsRef<str> for BigDecimal {
308 fn as_ref(&self) -> &str {
309 &self.0
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316 use std::str::FromStr;
317
318 #[test]
319 fn big_integer_basic() {
320 let bi = BigInteger::from_str("12345678901234567890").unwrap();
321 assert_eq!(bi.as_ref(), "12345678901234567890");
322 }
323
324 #[test]
325 fn big_integer_default() {
326 let bi = BigInteger::default();
327 assert_eq!(bi.as_ref(), "0");
328 assert_eq!(BigInteger::from_str(bi.as_ref()).unwrap(), bi);
330 }
331
332 #[test]
333 fn big_decimal_basic() {
334 let bd = BigDecimal::from_str("123.456789").unwrap();
335 assert_eq!(bd.as_ref(), "123.456789");
336 }
337
338 #[test]
339 fn big_decimal_default() {
340 let bd = BigDecimal::default();
341 assert_eq!(bd.as_ref(), "0.0");
342 assert_eq!(BigDecimal::from_str(bd.as_ref()).unwrap(), bd);
343 }
344
345 #[test]
346 fn big_integer_negative() {
347 let bi = BigInteger::from_str("-12345").unwrap();
348 assert_eq!(bi.as_ref(), "-12345");
349 }
350
351 #[test]
352 fn big_decimal_scientific() {
353 let bd = BigDecimal::from_str("1.23e10").unwrap();
354 assert_eq!(bd.as_ref(), "1.23e10");
355
356 let bd = BigDecimal::from_str("1.23E-10").unwrap();
357 assert_eq!(bd.as_ref(), "1.23E-10");
358 }
359
360 #[test]
361 fn big_decimal_accepts_supported_formats() {
362 for value in ["0", "+5", "-0.0", ".5", "-.5", "5.", "1.5E+3"] {
363 assert!(BigDecimal::from_str(value).is_ok(), "{value}");
364 }
365 }
366
367 #[test]
368 fn big_decimal_rejects_malformed_values() {
369 for value in [
370 "1.2.3", "-", "+", ".", "e", "E", "1e", "1e+", "--5", "1-2", "12-34", "..", "1.2e3.4",
371 "+-1",
372 ] {
373 assert_eq!(
374 BigDecimal::from_str(value),
375 Err(BigNumberError::InvalidFormat(value.to_string())),
376 "{value}"
377 );
378 }
379 }
380
381 #[test]
382 fn big_decimal_rejects_out_of_range_exponents() {
383 for value in [
384 "1E99999999999999999999",
385 "1E-99999999999999999999",
386 "1e9223372036854775808",
387 "1e-9223372036854775808",
388 "1e999999999999999999999999999999999999999",
389 ] {
390 assert_eq!(
391 BigDecimal::from_str(value),
392 Err(BigNumberError::ExponentOutOfRange(value.to_string())),
393 "{value}"
394 );
395 }
396 }
397
398 fn hash_of(value: &BigDecimal) -> u64 {
399 use std::hash::{BuildHasher, BuildHasherDefault};
400 BuildHasherDefault::<std::collections::hash_map::DefaultHasher>::default().hash_one(value)
401 }
402
403 fn assert_same_value(a: &str, b: &str) {
404 let (x, y) = (
405 BigDecimal::from_str(a).unwrap(),
406 BigDecimal::from_str(b).unwrap(),
407 );
408 assert_eq!(x, y, "{a} should equal {b}");
409 assert_eq!(hash_of(&x), hash_of(&y), "{a} and {b} should hash the same");
410 }
411
412 #[test]
413 fn big_decimal_compares_numeric_values_not_spellings() {
414 for (a, b) in [
415 ("1e2", "100"),
417 ("1.0", "1.00"),
418 ("+5", "5"),
419 ("-0.0", "0"),
420 (".5", "0.5"),
421 ("5.", "5"),
423 ("1.5E+3", "1500"),
424 ("150e1", "1.5e3"),
425 ("0.0012", "1.2e-3"),
426 ("12e-5", "0.00012"),
427 ("00123.4500", "123.45"),
428 ("-007e2", "-700"),
429 ("1E0", "1"),
430 ("10.0", "1e1"),
431 ("0", "-0"),
433 ("0.000", "0e50"),
434 ("-.0e-9", "+0"),
435 ("0.0", "0"),
436 ] {
437 assert_same_value(a, b);
438 }
439 }
440
441 #[test]
442 fn big_decimal_keeps_different_values_different() {
443 for (a, b) in [
444 ("1", "-1"),
445 ("1", "10"),
446 ("1.5", "15"),
447 ("0.1", "0.01"),
448 ("1e2", "1e3"),
449 ("12", "21"),
450 ("1.2", "1.02"),
451 ("100", "101"),
452 ("0", "1e-999"),
453 ("-0.5", "0.5"),
454 ] {
455 assert_ne!(
456 BigDecimal::from_str(a).unwrap(),
457 BigDecimal::from_str(b).unwrap(),
458 "{a} should not equal {b}"
459 );
460 }
461 }
462
463 #[test]
464 fn big_decimal_equality_keeps_the_original_spelling() {
465 let scientific = BigDecimal::from_str("1e2").unwrap();
466 let plain = BigDecimal::from_str("100").unwrap();
467 assert_eq!(scientific, plain);
468 assert_eq!(scientific.as_ref(), "1e2");
469 assert_eq!(plain.as_ref(), "100");
470 }
471
472 #[test]
473 fn big_decimal_works_as_a_hash_set_key() {
474 let values: std::collections::HashSet<BigDecimal> = ["100", "1e2", "100.000", "+1E+2", "7"]
475 .into_iter()
476 .map(|v| BigDecimal::from_str(v).unwrap())
477 .collect();
478 assert_eq!(values.len(), 2);
479 assert!(values.contains(&BigDecimal::from_str("10e1").unwrap()));
480 }
481
482 #[test]
483 fn big_decimal_default_equals_zero() {
484 assert_eq!(BigDecimal::default(), BigDecimal::from_str("0").unwrap());
485 }
486
487 #[test]
488 fn big_decimal_compares_exponents_at_the_supported_extremes() {
489 assert_same_value("1e9223372036854775807", "10e9223372036854775806");
490 assert_same_value("1e-9223372036854775806", "0.1e-9223372036854775805");
491 assert_ne!(
492 BigDecimal::from_str("1e9223372036854775807").unwrap(),
493 BigDecimal::from_str("1e9223372036854775806").unwrap()
494 );
495 }
496
497 mod numeric_equality {
498 use super::super::BigDecimal;
499 use proptest::prelude::*;
500 use std::str::FromStr;
501
502 fn spell(
505 negative: bool,
506 digits: &str,
507 exponent: i64,
508 shift: usize,
509 lead: usize,
510 trail: usize,
511 ) -> String {
512 let sign = if negative { "-" } else { "" };
513 let mut all = format!("{}{digits}{}", "0".repeat(lead), "0".repeat(trail));
514 if shift > all.len() {
516 all = format!("{}{all}", "0".repeat(shift - all.len()));
517 }
518 let point = all.len() - shift;
519 let exponent = exponent - trail as i64 + shift as i64;
520 format!("{sign}{}.{}e{exponent}", &all[..point], &all[point..])
521 }
522
523 proptest! {
524 #[test]
525 fn every_spelling_of_a_value_is_equal(
526 negative in any::<bool>(),
527 digits in "[1-9]([0-9]{0,20}[1-9])?",
528 exponent in -1000i64..1000,
529 shift_a in 0usize..30, lead_a in 0usize..5, trail_a in 0usize..5,
530 shift_b in 0usize..30, lead_b in 0usize..5, trail_b in 0usize..5,
531 ) {
532 let a = spell(negative, &digits, exponent, shift_a, lead_a, trail_a);
533 let b = spell(negative, &digits, exponent, shift_b, lead_b, trail_b);
534 let (x, y) = (BigDecimal::from_str(&a).unwrap(), BigDecimal::from_str(&b).unwrap());
535 prop_assert_eq!(&x, &y, "{} vs {}", a, b);
536 prop_assert_eq!(super::hash_of(&x), super::hash_of(&y));
537 }
538
539 #[test]
540 fn different_values_are_not_equal(
541 negative in any::<bool>(),
542 digits in "[1-9]([0-9]{0,20}[1-9])?",
543 exponent in -1000i64..1000,
544 bump in 1i64..5,
545 shift in 0usize..30,
546 ) {
547 let a = spell(negative, &digits, exponent, shift, 0, 0);
548 let b = spell(negative, &digits, exponent + bump, shift, 0, 0);
549 let c = spell(!negative, &digits, exponent, shift, 0, 0);
550 let x = BigDecimal::from_str(&a).unwrap();
551 prop_assert_ne!(&x, &BigDecimal::from_str(&b).unwrap(), "{} vs {}", a, b);
552 prop_assert_ne!(&x, &BigDecimal::from_str(&c).unwrap(), "{} vs {}", a, c);
553 }
554 }
555 }
556
557 #[test]
558 fn big_integer_rejects_json_injection() {
559 assert!(BigInteger::from_str("123, \"injected\": true").is_err());
561 assert!(BigInteger::from_str("123}").is_err());
562 assert!(BigInteger::from_str("{\"hacked\": 1}").is_err());
563 assert!(BigInteger::from_str("123\"").is_err());
564 assert!(BigInteger::from_str("123\\n456").is_err());
565 }
566
567 #[test]
568 fn big_decimal_rejects_json_injection() {
569 assert!(BigDecimal::from_str("123.45, \"injected\": true").is_err());
570 assert!(BigDecimal::from_str("123.45}").is_err());
571 assert!(BigDecimal::from_str("{\"hacked\": 1.0}").is_err());
572 }
573
574 #[test]
575 fn big_integer_rejects_invalid_chars() {
576 assert!(BigInteger::from_str("abc").is_err());
577 assert!(BigInteger::from_str("123abc").is_err());
578 assert!(BigInteger::from_str("12 34").is_err());
579 assert!(BigInteger::from_str("").is_err());
580 }
581
582 #[test]
583 fn big_integer_rejects_decimal_and_scientific() {
584 assert!(BigInteger::from_str("123.45").is_err());
586 assert!(BigInteger::from_str("123.0").is_err());
587
588 assert!(BigInteger::from_str("1e10").is_err());
590 assert!(BigInteger::from_str("1E10").is_err());
591 assert!(BigInteger::from_str("1.23e10").is_err());
592 }
593
594 #[test]
595 fn big_decimal_rejects_invalid_chars() {
596 assert!(BigDecimal::from_str("abc").is_err());
597 assert!(BigDecimal::from_str("123.45abc").is_err());
598 assert!(BigDecimal::from_str("12.34 56").is_err());
599 assert!(BigDecimal::from_str("").is_err());
600 }
601
602 #[test]
605 fn big_integer_rejects_a_leading_plus() {
606 assert!(BigInteger::from_str("+123").is_err());
609 assert!(BigInteger::from_str("+0").is_err());
610 }
611
612 #[test]
613 fn big_numbers_reject_bare_and_repeated_signs() {
614 for bad in ["-", "+", "--5", "++5", "-+5", "+-5", "5-", "5+"] {
615 assert!(
616 BigInteger::from_str(bad).is_err(),
617 "BigInteger::from_str({bad:?}) should fail"
618 );
619 assert!(
620 BigDecimal::from_str(bad).is_err(),
621 "BigDecimal::from_str({bad:?}) should fail"
622 );
623 }
624 }
625
626 #[test]
627 fn big_decimal_rejects_malformed_separators_and_exponents() {
628 for bad in [
629 "1..2", "1.2.3", "0.0.0", "1e", "1E", "1e+", "1e-", "e10", "-e10", "1e2e3", "1.5e", "1e2.5", "1e 2", "1 .5", ".", "1.2e3e", ] {
646 assert!(
647 BigDecimal::from_str(bad).is_err(),
648 "BigDecimal::from_str({bad:?}) should fail"
649 );
650 }
651 }
652
653 #[test]
654 fn big_decimal_accepts_additional_supported_formats() {
655 for good in [
656 "0",
657 "-0",
658 "123",
659 "-123",
660 "1.5",
661 "-0.5",
662 "1e3",
663 "1E3",
664 "1e+9",
665 "1e-9",
666 "1.23e10",
667 "1.23E-10",
668 "10.0",
669 "5e-3",
670 "0.123456789012345678901234567890",
671 "12345678901234567890.123",
672 "1.234e500",
673 ] {
674 let bd = BigDecimal::from_str(good)
675 .unwrap_or_else(|e| panic!("BigDecimal::from_str({good:?}) should succeed: {e}"));
676 assert_eq!(bd.as_ref(), good);
678 }
679 }
680
681 #[test]
682 fn big_numbers_still_accept_leading_zeros() {
683 for good in ["00123", "007", "-01", "0000", "-0000"] {
688 let bi = BigInteger::from_str(good)
689 .unwrap_or_else(|e| panic!("BigInteger::from_str({good:?}) should succeed: {e}"));
690 assert_eq!(bi.as_ref(), good);
691 let bd = BigDecimal::from_str(good)
692 .unwrap_or_else(|e| panic!("BigDecimal::from_str({good:?}) should succeed: {e}"));
693 assert_eq!(bd.as_ref(), good);
694 }
695 for good in ["00.1", "-01.5", "007e2"] {
696 let bd = BigDecimal::from_str(good)
697 .unwrap_or_else(|e| panic!("BigDecimal::from_str({good:?}) should succeed: {e}"));
698 assert_eq!(bd.as_ref(), good);
699 }
700 }
701
702 #[test]
703 fn big_integer_accepts_only_digits_after_an_optional_minus() {
704 for good in ["0", "-0", "1", "-1", "12345678901234567890"] {
705 assert!(
706 BigInteger::from_str(good).is_ok(),
707 "BigInteger::from_str({good:?}) should succeed"
708 );
709 }
710 for bad in ["1_000", "1,000", "0x1f", " 1", "1 ", "\t1", "1\n"] {
711 assert!(
712 BigInteger::from_str(bad).is_err(),
713 "BigInteger::from_str({bad:?}) should fail"
714 );
715 }
716 }
717
718 #[test]
719 fn big_number_error_reports_the_offending_input() {
720 let err = BigInteger::from_str("+123").unwrap_err();
721 assert_eq!(err, BigNumberError::InvalidFormat("+123".to_string()));
722 assert!(err.to_string().contains("+123"));
723 }
724
725 #[cfg(all(aws_sdk_unstable, feature = "serde-deserialize"))]
726 #[test]
727 fn serde_deserialization_preserves_big_number_invariants() {
728 let integer: BigInteger = serde_json::from_str(r#""00123""#).unwrap();
729 assert_eq!(integer.as_ref(), "00123");
730 assert!(serde_json::from_str::<BigInteger>(r#""+123""#).is_err());
731
732 for value in ["+5", ".5", "-.5", "5.", "1.5E+3"] {
733 let json = format!(r#""{value}""#);
734 let decimal: BigDecimal = serde_json::from_str(&json).unwrap();
735 assert_eq!(decimal.as_ref(), value);
736 }
737
738 for value in ["1.2.3", "--5", "1e"] {
739 let json = format!(r#""{value}""#);
740 assert!(serde_json::from_str::<BigDecimal>(&json).is_err());
741 }
742
743 let error = serde_json::from_str::<BigDecimal>(r#""1E99999999999999999999""#).unwrap_err();
744 assert!(error.to_string().contains("outside the supported range"));
745 }
746}