1use std::{borrow::Cow, cmp::Ordering, fmt::Display};
59
60use nautilus_core::correctness::{
61 CorrectnessError, CorrectnessResult, CorrectnessResultExt, FAILED,
62};
63use rust_decimal::Decimal;
64
65#[cfg(feature = "defi")]
66use crate::defi::WEI_PRECISION;
67use crate::types::{price::PriceRaw, quantity::QuantityRaw};
68
69#[unsafe(no_mangle)]
77#[allow(unsafe_code)]
78pub static HIGH_PRECISION_MODE: u8 = cfg!(feature = "high-precision") as u8;
79
80#[cfg(feature = "high-precision")]
85pub const FIXED_PRECISION: u8 = 16;
87
88pub const FIXED_PRECISION_STANDARD: u8 = 9;
90
91#[cfg(not(feature = "high-precision"))]
92pub const FIXED_PRECISION: u8 = FIXED_PRECISION_STANDARD;
94
95#[cfg(feature = "defi")]
96pub(crate) const MAX_PRECISION: u8 = WEI_PRECISION;
97
98#[cfg(not(feature = "defi"))]
99pub(crate) const MAX_PRECISION: u8 = FIXED_PRECISION;
100
101#[cfg(feature = "high-precision")]
106pub const PRECISION_BYTES: i32 = 16;
108
109#[cfg(not(feature = "high-precision"))]
110pub const PRECISION_BYTES: i32 = 8;
112
113pub const FIXED_DECIMAL: &str = "Decimal128(38, 16)";
115
116#[cfg(feature = "high-precision")]
121pub(crate) const FIXED_SCALAR_RAW: QuantityRaw = 10_000_000_000_000_000;
122
123#[cfg(not(feature = "high-precision"))]
124pub(crate) const FIXED_SCALAR_RAW: QuantityRaw = 1_000_000_000;
125
126#[cfg(feature = "high-precision")]
127pub const FIXED_SCALAR: f64 = 10_000_000_000_000_000.0;
129
130#[cfg(not(feature = "high-precision"))]
131pub const FIXED_SCALAR: f64 = 1_000_000_000.0;
133
134#[cfg(feature = "high-precision")]
139pub const PRECISION_DIFF_SCALAR: f64 = 10_000_000.0; #[cfg(not(feature = "high-precision"))]
143pub const PRECISION_DIFF_SCALAR: f64 = 1.0;
145
146const POWERS_OF_10: [u64; 17] = [
155 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000, 100_000_000_000, 1_000_000_000_000, 10_000_000_000_000, 100_000_000_000_000, 1_000_000_000_000_000, 10_000_000_000_000_000, ];
173
174const _: () = assert!(
177 (FIXED_PRECISION as usize) < POWERS_OF_10.len(),
178 "FIXED_PRECISION exceeds POWERS_OF_10 table size"
179);
180
181pub const MAX_FLOAT_PRECISION: u8 = 16;
192
193pub fn check_fixed_precision(precision: u8) -> CorrectnessResult<()> {
201 if precision > MAX_PRECISION {
202 let limit_name = if cfg!(feature = "defi") {
203 "WEI_PRECISION"
204 } else {
205 "FIXED_PRECISION"
206 };
207
208 return Err(CorrectnessError::PredicateViolation {
209 message: format!(
210 "`precision` exceeded maximum `{limit_name}` ({MAX_PRECISION}), was {precision}"
211 ),
212 });
213 }
214
215 Ok(())
216}
217
218pub fn check_float_precision(precision: u8) -> CorrectnessResult<()> {
224 if precision > MAX_FLOAT_PRECISION {
225 return Err(CorrectnessError::PredicateViolation {
226 message: format!(
227 "Fixed-point precision {precision} exceeds maximum float precision {MAX_FLOAT_PRECISION}"
228 ),
229 });
230 }
231
232 Ok(())
233}
234
235#[inline]
246#[must_use]
247pub fn raw_scales_match(a: u8, b: u8) -> bool {
248 a == b || a.max(b) <= FIXED_PRECISION
249}
250
251#[inline]
253#[must_use]
254pub(crate) fn raw_scale(precision: u8) -> u128 {
255 10_u128.pow(u32::from(precision.max(FIXED_PRECISION)))
256}
257
258#[must_use]
260pub(crate) fn canonical_raw(raw: impl Into<u128>, precision: u8) -> (u128, u8) {
261 let mut raw = raw.into();
262 let mut precision = if raw == 0 {
263 FIXED_PRECISION
264 } else {
265 precision.max(FIXED_PRECISION)
266 };
267
268 while precision > FIXED_PRECISION && raw % 10 == 0 {
269 raw /= 10;
270 precision -= 1;
271 }
272
273 (raw, precision)
274}
275
276#[inline]
277#[must_use]
278pub(crate) fn compare_raw_signed(
279 lhs: PriceRaw,
280 lhs_precision: u8,
281 rhs: PriceRaw,
282 rhs_precision: u8,
283) -> Ordering {
284 if raw_scales_match(lhs_precision, rhs_precision) {
285 return lhs.cmp(&rhs);
286 }
287
288 lhs.signum().cmp(&rhs.signum()).then_with(|| {
289 let ordering = compare_raw(
290 lhs.unsigned_abs(),
291 lhs_precision,
292 rhs.unsigned_abs(),
293 rhs_precision,
294 );
295
296 if lhs < 0 {
297 ordering.reverse()
298 } else {
299 ordering
300 }
301 })
302}
303
304#[inline]
305#[must_use]
306pub(crate) fn compare_raw(
307 lhs: impl Into<u128>,
308 lhs_precision: u8,
309 rhs: impl Into<u128>,
310 rhs_precision: u8,
311) -> Ordering {
312 let lhs = lhs.into();
313 let rhs = rhs.into();
314
315 if (lhs == 0 && rhs == 0) || raw_scales_match(lhs_precision, rhs_precision) {
317 return lhs.cmp(&rhs);
318 }
319
320 let lhs_scale = raw_scale(lhs_precision);
321 let rhs_scale = raw_scale(rhs_precision);
322 let scale = lhs_scale.max(rhs_scale);
323
324 (lhs / lhs_scale).cmp(&(rhs / rhs_scale)).then_with(|| {
326 let lhs_fraction = (lhs % lhs_scale) * (scale / lhs_scale);
327 let rhs_fraction = (rhs % rhs_scale) * (scale / rhs_scale);
328 lhs_fraction.cmp(&rhs_fraction)
329 })
330}
331
332#[must_use]
341pub(crate) fn scaled_raw_to_decimal(scaled_raw: i128, precision: u8) -> Decimal {
342 let scale = u32::from(precision);
343
344 Decimal::try_from_i128_with_scale(scaled_raw, scale).unwrap_or_else(|_| {
345 let divisor = 10_i128.pow(scale);
346
347 Decimal::from(scaled_raw / divisor)
348 + Decimal::from_i128_with_scale(scaled_raw % divisor, scale)
349 })
350}
351
352pub(crate) fn format_scaled_i128(raw: i128, precision: u8) -> String {
353 let sign = if raw < 0 { "-" } else { "" };
354 format!(
355 "{sign}{}",
356 format_scaled_u128(raw.unsigned_abs(), precision)
357 )
358}
359
360pub(crate) fn parse_decimal_mantissa(value: &str) -> Result<(i128, u8), String> {
362 let (negative, unsigned) = value
363 .strip_prefix('-')
364 .map_or((false, value), |value| (true, value));
365 let unsigned = if negative {
366 unsigned
367 } else {
368 unsigned.strip_prefix('+').unwrap_or(unsigned)
369 };
370 let (whole, fraction) = unsigned.split_once('.').unwrap_or((unsigned, ""));
371 if fraction.contains('.') {
372 return Err(format!("Invalid decimal value '{value}'"));
373 }
374
375 let digits = whole.bytes().chain(fraction.bytes());
376 if (whole.is_empty() && fraction.is_empty())
377 || !digits.clone().all(|byte| byte.is_ascii_digit())
378 {
379 return Err(format!("Invalid decimal value '{value}'"));
380 }
381 let precision = u8::try_from(fraction.len())
382 .map_err(|_| format!("Decimal value '{value}' has too many fractional digits"))?;
383 let mut mantissa = 0_i128;
384 for digit in digits.map(|byte| i128::from(byte - b'0')) {
385 mantissa = if negative {
386 mantissa
387 .checked_mul(10)
388 .and_then(|value| value.checked_sub(digit))
389 } else {
390 mantissa
391 .checked_mul(10)
392 .and_then(|value| value.checked_add(digit))
393 }
394 .ok_or_else(|| format!("Decimal value '{value}' exceeds i128 range"))?;
395 }
396 Ok((mantissa, precision))
397}
398
399pub(super) fn remove_underscores(value: &str) -> Cow<'_, str> {
400 if value.contains('_') {
401 Cow::Owned(value.replace('_', ""))
402 } else {
403 Cow::Borrowed(value)
404 }
405}
406
407pub(crate) fn format_scaled_u128(raw: u128, precision: u8) -> String {
408 if precision == 0 {
409 return raw.to_string();
410 }
411
412 let scale = 10_u128.pow(u32::from(precision));
413 format!(
414 "{}.{:0>width$}",
415 raw / scale,
416 raw % scale,
417 width = usize::from(precision),
418 )
419}
420
421#[must_use]
425pub(crate) fn checked_mul_div_fixed(lhs: QuantityRaw, rhs: QuantityRaw) -> Option<QuantityRaw> {
426 checked_mul_div_raw(lhs, rhs, FIXED_SCALAR_RAW)
427}
428
429#[must_use]
432pub(crate) fn checked_mul_div_raw(
433 lhs: QuantityRaw,
434 rhs: QuantityRaw,
435 scalar: QuantityRaw,
436) -> Option<QuantityRaw> {
437 let lhs_whole = lhs / scalar;
438 let lhs_remainder = lhs % scalar;
439 let rhs_whole = rhs / scalar;
440 let rhs_remainder = rhs % scalar;
441
442 lhs_whole
443 .checked_mul(rhs)
444 .and_then(|whole| {
445 lhs_remainder
446 .checked_mul(rhs_whole)
447 .and_then(|mixed| whole.checked_add(mixed))
448 })
449 .and_then(|whole_and_mixed| {
450 lhs_remainder
451 .checked_mul(rhs_remainder)
452 .map(|fractional| fractional / scalar)
453 .and_then(|fractional| whole_and_mixed.checked_add(fractional))
454 })
455}
456
457const _: () = {
458 assert!(FIXED_SCALAR_RAW > 0);
459 assert!((FIXED_SCALAR_RAW as f64).to_bits() == FIXED_SCALAR.to_bits());
460 let max_remainder = FIXED_SCALAR_RAW - 1;
461 assert!(max_remainder.checked_mul(max_remainder).is_some());
462};
463
464#[inline(always)]
474fn should_skip_validation(precision: u8) -> bool {
475 #[cfg(not(feature = "defi"))]
476 debug_assert!(
477 precision <= FIXED_PRECISION,
478 "precision {precision} exceeds FIXED_PRECISION {FIXED_PRECISION}: \
479 raw value validation is not possible at this precision"
480 );
481
482 precision >= FIXED_PRECISION
483}
484
485#[cold]
487fn invalid_raw_error(
488 raw: impl Display,
489 precision: u8,
490 remainder: impl Display,
491 scale: impl Display,
492) -> anyhow::Error {
493 anyhow::anyhow!(
494 "Invalid fixed-point raw value {raw} for precision {precision}: \
495 remainder {remainder} when divided by scale {scale}. \
496 Raw value should be a multiple of {scale}. \
497 This indicates data corruption or incorrect precision/scaling upstream"
498 )
499}
500
501#[inline(always)]
531pub fn check_fixed_raw_u128(raw: u128, precision: u8) -> anyhow::Result<()> {
532 if should_skip_validation(precision) {
533 return Ok(());
534 }
535
536 let exp = usize::from(FIXED_PRECISION - precision);
537 let scale = u128::from(POWERS_OF_10[exp]);
538 let remainder = raw % scale;
539
540 if remainder != 0 {
541 return Err(invalid_raw_error(raw, precision, remainder, scale));
542 }
543
544 Ok(())
545}
546
547#[inline(always)]
556pub fn check_fixed_raw_u64(raw: u64, precision: u8) -> anyhow::Result<()> {
557 if should_skip_validation(precision) {
558 return Ok(());
559 }
560
561 let exp = usize::from(FIXED_PRECISION - precision);
562 let scale = POWERS_OF_10[exp];
563 let remainder = raw % scale;
564
565 if remainder != 0 {
566 return Err(invalid_raw_error(raw, precision, remainder, scale));
567 }
568
569 Ok(())
570}
571
572#[inline(always)]
602pub fn check_fixed_raw_i128(raw: i128, precision: u8) -> anyhow::Result<()> {
603 if should_skip_validation(precision) {
604 return Ok(());
605 }
606
607 let exp = usize::from(FIXED_PRECISION - precision);
608 let scale = i128::from(POWERS_OF_10[exp]);
609 let remainder = raw % scale;
610
611 if remainder != 0 {
612 return Err(invalid_raw_error(raw, precision, remainder, scale));
613 }
614
615 Ok(())
616}
617
618#[inline(always)]
627pub fn check_fixed_raw_i64(raw: i64, precision: u8) -> anyhow::Result<()> {
628 if should_skip_validation(precision) {
629 return Ok(());
630 }
631
632 let exp = usize::from(FIXED_PRECISION - precision);
633 let scale = POWERS_OF_10[exp].cast_signed();
634 let remainder = raw % scale;
635
636 if remainder != 0 {
637 return Err(invalid_raw_error(raw, precision, remainder, scale));
638 }
639
640 Ok(())
641}
642
643#[must_use]
660pub fn correct_raw_u128(raw: u128, precision: u8) -> u128 {
661 if precision >= FIXED_PRECISION {
662 return raw;
663 }
664 let exp = usize::from(FIXED_PRECISION - precision);
665 let scale = u128::from(POWERS_OF_10[exp]);
666 let half_scale = scale / 2;
667 let remainder = raw % scale;
668 if remainder == 0 {
669 raw
670 } else if remainder >= half_scale {
671 raw.checked_add(scale - remainder)
672 .unwrap_or(raw - remainder)
673 } else {
674 raw - remainder
675 }
676}
677
678#[must_use]
686pub fn correct_raw_u64(raw: u64, precision: u8) -> u64 {
687 if precision >= FIXED_PRECISION {
688 return raw;
689 }
690 let exp = usize::from(FIXED_PRECISION - precision);
691 let scale = POWERS_OF_10[exp];
692 let half_scale = scale / 2;
693 let remainder = raw % scale;
694 if remainder == 0 {
695 raw
696 } else if remainder >= half_scale {
697 raw.checked_add(scale - remainder)
698 .unwrap_or(raw - remainder)
699 } else {
700 raw - remainder
701 }
702}
703
704#[must_use]
712pub fn correct_raw_i128(raw: i128, precision: u8) -> i128 {
713 if precision >= FIXED_PRECISION {
714 return raw;
715 }
716 let exp = usize::from(FIXED_PRECISION - precision);
717 let scale = i128::from(POWERS_OF_10[exp]);
718 let half_scale = scale / 2;
719 let remainder = raw % scale;
720 if remainder == 0 {
721 raw
722 } else if raw >= 0 {
723 if remainder >= half_scale {
724 raw.checked_add(scale - remainder)
725 .unwrap_or(raw - remainder)
726 } else {
727 raw - remainder
728 }
729 } else {
730 if remainder.abs() >= half_scale {
732 raw.checked_sub(scale + remainder)
733 .unwrap_or(raw - remainder)
734 } else {
735 raw - remainder
736 }
737 }
738}
739
740#[must_use]
748pub fn correct_raw_i64(raw: i64, precision: u8) -> i64 {
749 if precision >= FIXED_PRECISION {
750 return raw;
751 }
752 let exp = usize::from(FIXED_PRECISION - precision);
753 let scale = POWERS_OF_10[exp].cast_signed();
754 let half_scale = scale / 2;
755 let remainder = raw % scale;
756 if remainder == 0 {
757 raw
758 } else if raw >= 0 {
759 if remainder >= half_scale {
760 raw.checked_add(scale - remainder)
761 .unwrap_or(raw - remainder)
762 } else {
763 raw - remainder
764 }
765 } else {
766 if remainder.abs() >= half_scale {
768 raw.checked_sub(scale + remainder)
769 .unwrap_or(raw - remainder)
770 } else {
771 raw - remainder
772 }
773 }
774}
775
776#[must_use]
782#[inline]
783pub fn correct_price_raw(raw: PriceRaw, precision: u8) -> PriceRaw {
784 #[cfg(feature = "high-precision")]
785 {
786 correct_raw_i128(raw, precision)
787 }
788 #[cfg(not(feature = "high-precision"))]
789 {
790 correct_raw_i64(raw, precision)
791 }
792}
793
794#[must_use]
800#[inline]
801pub fn correct_quantity_raw(raw: QuantityRaw, precision: u8) -> QuantityRaw {
802 #[cfg(feature = "high-precision")]
803 {
804 correct_raw_u128(raw, precision)
805 }
806 #[cfg(not(feature = "high-precision"))]
807 {
808 correct_raw_u64(raw, precision)
809 }
810}
811
812#[must_use]
817#[inline]
818pub fn bankers_round(mantissa: i128, excess: u32) -> i128 {
819 if excess == 0 {
820 return mantissa;
821 }
822
823 if excess >= 39 {
825 return 0;
826 }
827
828 let divisor = 10i128.pow(excess);
829 let quotient = mantissa / divisor;
830 let remainder = mantissa % divisor;
831 let half = divisor / 2;
832
833 if remainder.abs() > half || (remainder.abs() == half && quotient % 2 != 0) {
834 quotient + mantissa.signum()
835 } else {
836 quotient
837 }
838}
839
840pub fn mantissa_exponent_to_fixed_i128(
855 mantissa: i128,
856 exponent: i8,
857 precision: u8,
858) -> CorrectnessResult<i128> {
859 check_fixed_precision(precision)?;
860
861 let precision_i16 = i16::from(precision);
862 let target_scale = i16::from(FIXED_PRECISION).max(precision_i16);
863 let frac_digits = -i16::from(exponent);
864
865 let mantissa = if frac_digits > precision_i16 {
866 let excess = u32::from((frac_digits - precision_i16).cast_unsigned());
867 bankers_round(mantissa, excess)
868 } else {
869 mantissa
870 };
871
872 let scale_after_rounding = frac_digits.min(precision_i16);
873 let scale_exp = target_scale - scale_after_rounding;
874 if scale_exp > 38 {
875 return Err(CorrectnessError::PredicateViolation {
876 message: format!(
877 "Exponent {exponent} produces scale factor 10^{scale_exp} which exceeds i128 range"
878 ),
879 });
880 }
881
882 if scale_exp >= 0 {
883 mantissa.checked_mul(10i128.pow(u32::from(scale_exp.cast_unsigned())))
884 } else {
885 Some(mantissa / 10i128.pow(u32::from((-scale_exp).cast_unsigned())))
886 }
887 .ok_or_else(|| CorrectnessError::PredicateViolation {
888 message: "Overflow when scaling mantissa to fixed precision".to_string(),
889 })
890}
891
892pub(crate) fn mantissa_exponent_to_raw_checked<R>(
893 mantissa: i128,
894 exponent: i8,
895 precision: u8,
896 context: &'static str,
897 raw_type_name: &'static str,
898 value_type_name: &'static str,
899) -> CorrectnessResult<R>
900where
901 R: TryFrom<i128>,
902{
903 check_fixed_precision(precision)?;
904
905 let raw_i128 = if mantissa == 0 {
906 0
907 } else {
908 mantissa_exponent_to_fixed_i128(mantissa, exponent, precision).map_err(|_| {
909 CorrectnessError::PredicateViolation {
910 message: format!(
911 "Overflow in {context} (mantissa={mantissa}, exponent={exponent}, precision={precision})"
912 ),
913 }
914 })?
915 };
916
917 raw_i128
918 .try_into()
919 .map_err(|_| CorrectnessError::PredicateViolation {
920 message: format!(
921 "Raw value {raw_i128} exceeds {raw_type_name} range for {value_type_name}"
922 ),
923 })
924}
925
926#[must_use]
943#[expect(
944 clippy::cast_precision_loss,
945 clippy::cast_possible_truncation,
946 reason = "f64 to fixed-point conversion is inherently lossy; callers validate range and finiteness"
947)]
948pub fn f64_to_fixed_i64(value: f64, precision: u8) -> i64 {
949 check_fixed_precision(precision).expect_display(FAILED);
950 let pow1 = 10_i64.pow(u32::from(precision));
951 let pow2 = 10_i64.pow(u32::from(FIXED_PRECISION - precision));
952 let rounded = (value * pow1 as f64).round() as i64;
953 rounded
954 .checked_mul(pow2)
955 .expect("Overflow when scaling f64 to fixed-point i64")
956}
957
958#[must_use]
968#[expect(
969 clippy::cast_precision_loss,
970 clippy::cast_possible_truncation,
971 reason = "f64 to fixed-point conversion is inherently lossy; callers validate range and finiteness"
972)]
973pub fn f64_to_fixed_i128(value: f64, precision: u8) -> i128 {
974 check_fixed_precision(precision).expect_display(FAILED);
975 let pow1 = 10_i128.pow(u32::from(precision));
976 let pow2 = 10_i128.pow(u32::from(FIXED_PRECISION - precision));
977 let rounded = (value * pow1 as f64).round() as i128;
978 rounded
979 .checked_mul(pow2)
980 .expect("Overflow when scaling f64 to fixed-point i128")
981}
982
983#[must_use]
993#[expect(
994 clippy::cast_precision_loss,
995 clippy::cast_possible_truncation,
996 clippy::cast_sign_loss,
997 reason = "f64 to fixed-point conversion is inherently lossy; callers validate range and finiteness"
998)]
999pub fn f64_to_fixed_u64(value: f64, precision: u8) -> u64 {
1000 check_fixed_precision(precision).expect_display(FAILED);
1001 let pow1 = 10_u64.pow(u32::from(precision));
1002 let pow2 = 10_u64.pow(u32::from(FIXED_PRECISION - precision));
1003 let rounded = (value * pow1 as f64).round() as u64;
1004 rounded
1005 .checked_mul(pow2)
1006 .expect("Overflow when scaling f64 to fixed-point u64")
1007}
1008
1009#[must_use]
1019#[expect(
1020 clippy::cast_precision_loss,
1021 clippy::cast_possible_truncation,
1022 clippy::cast_sign_loss,
1023 reason = "f64 to fixed-point conversion is inherently lossy; callers validate range and finiteness"
1024)]
1025pub fn f64_to_fixed_u128(value: f64, precision: u8) -> u128 {
1026 check_fixed_precision(precision).expect_display(FAILED);
1027 let pow1 = 10_u128.pow(u32::from(precision));
1028 let pow2 = 10_u128.pow(u32::from(FIXED_PRECISION - precision));
1029 let rounded = (value * pow1 as f64).round() as u128;
1030 rounded
1031 .checked_mul(pow2)
1032 .expect("Overflow when scaling f64 to fixed-point u128")
1033}
1034
1035#[must_use]
1037#[expect(
1038 clippy::cast_precision_loss,
1039 reason = "i64 to f64 is inherently lossy above 2^53; accepted for float interop"
1040)]
1041pub fn fixed_i64_to_f64(value: i64) -> f64 {
1042 (value as f64) / FIXED_SCALAR
1043}
1044
1045#[must_use]
1047#[expect(
1048 clippy::cast_precision_loss,
1049 reason = "i128 to f64 is inherently lossy above 2^53; accepted for float interop"
1050)]
1051pub fn fixed_i128_to_f64(value: i128) -> f64 {
1052 (value as f64) / FIXED_SCALAR
1053}
1054
1055#[must_use]
1057#[expect(
1058 clippy::cast_precision_loss,
1059 reason = "u64 to f64 is inherently lossy above 2^53; accepted for float interop"
1060)]
1061pub fn fixed_u64_to_f64(value: u64) -> f64 {
1062 (value as f64) / FIXED_SCALAR
1063}
1064
1065#[must_use]
1067#[expect(
1068 clippy::cast_precision_loss,
1069 reason = "u128 to f64 is inherently lossy above 2^53; accepted for float interop"
1070)]
1071pub fn fixed_u128_to_f64(value: u128) -> f64 {
1072 (value as f64) / FIXED_SCALAR
1073}
1074
1075#[cfg(feature = "high-precision")]
1076#[cfg(test)]
1077mod tests {
1078 use nautilus_core::approx_eq;
1079 use rstest::rstest;
1080
1081 use super::*;
1082
1083 #[rstest]
1084 fn test_correct_raw_rounds_half_away_from_zero() {
1085 let precision = FIXED_PRECISION - 1;
1086
1087 assert_eq!(correct_raw_u128(20, precision), 20);
1088 assert_eq!(correct_raw_u128(14, precision), 10);
1089 assert_eq!(correct_raw_u128(15, precision), 20);
1090 assert_eq!(correct_raw_u64(14, precision), 10);
1091 assert_eq!(correct_raw_u64(15, precision), 20);
1092 assert_eq!(correct_raw_i128(15, precision), 20);
1093 assert_eq!(correct_raw_i128(-14, precision), -10);
1094 assert_eq!(correct_raw_i128(-15, precision), -20);
1095 assert_eq!(correct_raw_i64(15, precision), 20);
1096 assert_eq!(correct_raw_i64(-14, precision), -10);
1097 assert_eq!(correct_raw_i64(-15, precision), -20);
1098 }
1099
1100 #[rstest]
1101 fn test_f64_fixed_u128_round_trip() {
1102 let raw = f64_to_fixed_u128(1.5, 1);
1103
1104 assert_eq!(raw, 15 * 10_u128.pow(u32::from(FIXED_PRECISION - 1)));
1105 assert_eq!(fixed_u128_to_f64(raw), 1.5);
1106 }
1107
1108 #[rstest]
1109 fn test_mantissa_exponent_to_fixed_i128_allows_max_scale_factor() {
1110 let exponent = i8::try_from(38 - FIXED_PRECISION).unwrap();
1111
1112 assert_eq!(
1113 mantissa_exponent_to_fixed_i128(1, exponent, 0).unwrap(),
1114 10_i128.pow(38)
1115 );
1116 assert_eq!(
1117 mantissa_exponent_to_fixed_i128(1, exponent + 1, 0)
1118 .unwrap_err()
1119 .to_string(),
1120 format!(
1121 "Exponent {} produces scale factor 10^39 which exceeds i128 range",
1122 exponent + 1
1123 )
1124 );
1125 }
1126
1127 #[rstest]
1128 fn test_raw_scales_match_requires_equal_effective_scale() {
1129 assert!(raw_scales_match(0, FIXED_PRECISION));
1130 assert!(raw_scales_match(FIXED_PRECISION + 1, FIXED_PRECISION + 1));
1131 assert!(!raw_scales_match(FIXED_PRECISION, FIXED_PRECISION + 1));
1132 }
1133
1134 #[rstest]
1135 fn test_canonical_raw_trims_native_scale_trailing_zeros() {
1136 assert_eq!(
1137 canonical_raw(0_u128, FIXED_PRECISION + 2),
1138 (0, FIXED_PRECISION)
1139 );
1140 assert_eq!(
1141 canonical_raw(1_200_u128, FIXED_PRECISION + 2),
1142 (12, FIXED_PRECISION)
1143 );
1144 assert_eq!(
1145 canonical_raw(12_000_u128, FIXED_PRECISION + 2),
1146 (120, FIXED_PRECISION)
1147 );
1148 assert_eq!(
1149 canonical_raw(1_205_u128, FIXED_PRECISION + 2),
1150 (1_205, FIXED_PRECISION + 2)
1151 );
1152 assert_eq!(
1153 canonical_raw(5_u128, FIXED_PRECISION - 1),
1154 (5, FIXED_PRECISION)
1155 );
1156 }
1157
1158 #[rstest]
1159 fn test_compare_raw_zero_operands_are_equal_across_scales() {
1160 assert_eq!(compare_raw(0_u128, u8::MAX, 0_u128, 2), Ordering::Equal);
1161 }
1162
1163 #[rstest]
1164 #[case("")]
1165 #[case("0")]
1166 #[case("-12.3400")]
1167 #[case("+1e9")]
1168 #[case("not decimal")]
1169 fn test_remove_underscores_borrows_clean_values(#[case] input: &str) {
1170 assert!(matches!(remove_underscores(input), Cow::Borrowed(value) if value == input));
1171 }
1172
1173 #[rstest]
1174 #[case("_", "")]
1175 #[case("1_234.56", "1234.56")]
1176 #[case("_1__2_3.4_5_", "123.45")]
1177 #[case("1e_3", "1e3")]
1178 #[case("_-_1_0_._0_", "-10.0")]
1179 fn test_remove_underscores_removes_separators(#[case] input: &str, #[case] expected: &str) {
1180 assert!(matches!(remove_underscores(input), Cow::Owned(value) if value == expected));
1181 }
1182
1183 #[rstest]
1184 #[case("1.00", 100, 2)]
1185 #[case("+1.00", 100, 2)]
1186 #[case("-1.00", -100, 2)]
1187 #[case("-0.00", 0, 2)]
1188 fn test_parse_decimal_mantissa_sign(
1189 #[case] input: &str,
1190 #[case] mantissa: i128,
1191 #[case] precision: u8,
1192 ) {
1193 assert_eq!(parse_decimal_mantissa(input), Ok((mantissa, precision)));
1194 }
1195
1196 #[rstest]
1197 #[case("-+1.00")]
1198 #[case("+-1.00")]
1199 #[case("--1.00")]
1200 #[case("++1.00")]
1201 #[case("-+0.00")]
1202 fn test_parse_decimal_mantissa_rejects_multiple_signs(#[case] input: &str) {
1203 assert_eq!(
1204 parse_decimal_mantissa(input),
1205 Err(format!("Invalid decimal value '{input}'")),
1206 );
1207 assert!(input.parse::<crate::types::Price>().is_err());
1208 assert!(input.parse::<crate::types::Quantity>().is_err());
1209 assert!(
1210 format!("{input} USD")
1211 .parse::<crate::types::Money>()
1212 .is_err()
1213 );
1214 }
1215
1216 #[rstest]
1217 #[case(i128::MIN)]
1218 #[case(i128::MAX)]
1219 fn test_parse_decimal_mantissa_integer_limits(#[case] value: i128) {
1220 assert_eq!(parse_decimal_mantissa(&value.to_string()), Ok((value, 0)));
1221 }
1222
1223 #[rstest]
1224 #[case("170141183460469231731687303715884105728")]
1225 #[case("-170141183460469231731687303715884105729")]
1226 fn test_parse_decimal_mantissa_overflow(#[case] input: &str) {
1227 assert_eq!(
1228 parse_decimal_mantissa(input),
1229 Err(format!("Decimal value '{input}' exceeds i128 range")),
1230 );
1231 }
1232
1233 #[rstest]
1234 #[case(".5", 5, 1)]
1235 #[case("-.5", -5, 1)]
1236 #[case("1.", 1, 0)]
1237 #[case("0001.0200", 10200, 4)]
1238 fn test_parse_decimal_mantissa_syntax(
1239 #[case] input: &str,
1240 #[case] mantissa: i128,
1241 #[case] precision: u8,
1242 ) {
1243 assert_eq!(parse_decimal_mantissa(input), Ok((mantissa, precision)));
1244 }
1245
1246 #[rstest]
1247 #[case("")]
1248 #[case(".")]
1249 #[case("+")]
1250 #[case("-")]
1251 #[case("1.2.3")]
1252 #[case(" 1")]
1253 #[case("1 ")]
1254 #[case("1 2")]
1255 #[case("1")]
1256 fn test_parse_decimal_mantissa_invalid_syntax(#[case] input: &str) {
1257 assert_eq!(
1258 parse_decimal_mantissa(input),
1259 Err(format!("Invalid decimal value '{input}'")),
1260 );
1261 }
1262
1263 #[rstest]
1264 fn test_parse_decimal_mantissa_fraction_length_limit() {
1265 let accepted = format!("0.{}", "0".repeat(255));
1266 let rejected = format!("{accepted}0");
1267
1268 assert_eq!(parse_decimal_mantissa(&accepted), Ok((0, 255)));
1269 assert_eq!(
1270 parse_decimal_mantissa(&rejected),
1271 Err(format!(
1272 "Decimal value '{rejected}' has too many fractional digits"
1273 )),
1274 );
1275 }
1276
1277 #[rstest]
1278 fn test_decimal_string_domain_precision_limit() {
1279 use crate::types::{Price, Quantity};
1280
1281 #[cfg(feature = "defi")]
1282 let precision = crate::defi::WEI_PRECISION;
1283 #[cfg(not(feature = "defi"))]
1284 let precision = FIXED_PRECISION;
1285 let accepted = format!("0.{}1", "0".repeat(usize::from(precision - 1)));
1286 let rejected = format!("{accepted}0");
1287 let price = accepted.parse::<Price>().unwrap();
1288 let quantity = accepted.parse::<Quantity>().unwrap();
1289
1290 assert_eq!(price.raw, 1);
1291 assert_eq!(price.precision, precision);
1292 assert_eq!(quantity.raw, 1);
1293 assert_eq!(quantity.precision, precision);
1294 assert!(rejected.parse::<Price>().is_err());
1295 assert!(rejected.parse::<Quantity>().is_err());
1296 }
1297
1298 #[rstest]
1299 #[case(0, 0, "0")]
1300 #[case(125, 2, "1.25")]
1301 #[case(-1234, 2, "-12.34")]
1302 #[case(1, 16, "0.0000000000000001")]
1303 #[case(-1, 16, "-0.0000000000000001")]
1304 #[case(1_000_000_000_000_000_000, 18, "1.000000000000000000")]
1305 fn test_scaled_raw_to_decimal_matches_plain_conversion(
1306 #[case] raw: i128,
1307 #[case] precision: u8,
1308 #[case] expected: &str,
1309 ) {
1310 let plain = Decimal::from_i128_with_scale(raw, u32::from(precision));
1311 let result = scaled_raw_to_decimal(raw, precision);
1312
1313 assert_eq!(result, plain);
1314 assert_eq!(result.scale(), plain.scale());
1315 assert_eq!(result.to_string(), expected);
1316 }
1317
1318 #[rstest]
1319 #[case(80_000_000_000_000_000_000_000_000_000, 16, "8000000000000")]
1320 #[case(340_282_366_920_930_000_000_000_000_000, 16, "34028236692093")]
1321 #[case(170_141_183_460_460_000_000_000_000_000, 16, "17014118346046")]
1322 #[case(-170_141_183_460_460_000_000_000_000_000, 16, "-17014118346046")]
1323 #[case(
1326 80_000_000_000_000_005_000_000_000_000,
1327 16,
1328 "8000000000000.000500000000000"
1329 )]
1330 #[case(-80_000_000_000_000_005_000_000_000_000, 16, "-8000000000000.000500000000000")]
1331 #[case(
1332 80_000_000_000_000_000_000_000_000_001,
1333 16,
1334 "8000000000000.000000000000000"
1335 )]
1336 #[case(
1337 80_000_000_000_000_000_250_000_000_000,
1338 18,
1339 "80000000000.00000025000000000"
1340 )]
1341 #[case(-80_000_000_000_000_000_250_000_000_000, 18, "-80000000000.00000025000000000")]
1342 fn test_scaled_raw_to_decimal_beyond_mantissa_rounds_rather_than_panics(
1343 #[case] raw: i128,
1344 #[case] precision: u8,
1345 #[case] expected: &str,
1346 ) {
1347 assert_eq!(scaled_raw_to_decimal(raw, precision).to_string(), expected);
1351 }
1352
1353 #[cfg(not(feature = "defi"))]
1354 #[rstest]
1355 fn test_precision_boundaries() {
1356 assert!(check_fixed_precision(0).is_ok());
1357 assert!(check_fixed_precision(FIXED_PRECISION).is_ok());
1358 assert!(check_fixed_precision(FIXED_PRECISION + 1).is_err());
1359 }
1360
1361 #[cfg(feature = "defi")]
1362 #[rstest]
1363 fn test_precision_boundaries() {
1364 use crate::defi::WEI_PRECISION;
1365
1366 assert!(check_fixed_precision(0).is_ok());
1367 assert!(check_fixed_precision(WEI_PRECISION).is_ok());
1368 assert!(check_fixed_precision(WEI_PRECISION + 1).is_err());
1369 }
1370
1371 #[rstest]
1372 #[case(0.0)]
1373 #[case(1.0)]
1374 #[case(-1.0)]
1375 fn test_basic_roundtrip(#[case] value: f64) {
1376 for precision in 0..=FIXED_PRECISION {
1377 let fixed = f64_to_fixed_i128(value, precision);
1378 let result = fixed_i128_to_f64(fixed);
1379 assert!(approx_eq!(f64, value, result, epsilon = 0.001));
1380 }
1381 }
1382
1383 #[rstest]
1384 #[case(1_000_000.0)]
1385 #[case(-1_000_000.0)]
1386 fn test_large_value_roundtrip(#[case] value: f64) {
1387 for precision in 0..=FIXED_PRECISION {
1388 let fixed = f64_to_fixed_i128(value, precision);
1389 let result = fixed_i128_to_f64(fixed);
1390 assert!(approx_eq!(f64, value, result, epsilon = 0.000_1));
1391 }
1392 }
1393
1394 #[rstest]
1395 #[case(0, 123_456.0)]
1396 #[case(0, 123_456.7)]
1397 #[case(1, 123_456.7)]
1398 #[case(2, 123_456.78)]
1399 #[case(8, 123_456.123_456_78)]
1400 fn test_precision_specific_values_basic(#[case] precision: u8, #[case] value: f64) {
1401 let result = f64_to_fixed_i128(value, precision);
1402 let back_converted = fixed_i128_to_f64(result);
1403 let scale = 10.0_f64.powi(i32::from(precision));
1405 let expected_rounded = (value * scale).round() / scale;
1406 assert!((back_converted - expected_rounded).abs() < 1e-10);
1407 }
1408
1409 #[rstest]
1410 fn test_max_precision_values() {
1411 let test_value = 123_456.123_456_789;
1413 let result = f64_to_fixed_i128(test_value, FIXED_PRECISION);
1414 let back_converted = fixed_i128_to_f64(result);
1415 assert!((back_converted - test_value).abs() < 1e-6);
1417 }
1418
1419 #[rstest]
1420 #[case(0.0)]
1421 #[case(1.0)]
1422 #[case(1_000_000.0)]
1423 fn test_unsigned_basic_roundtrip(#[case] value: f64) {
1424 for precision in 0..=FIXED_PRECISION {
1425 let fixed = f64_to_fixed_u128(value, precision);
1426 let result = fixed_u128_to_f64(fixed);
1427 assert!(approx_eq!(f64, value, result, epsilon = 0.001));
1428 }
1429 }
1430
1431 #[rstest]
1432 #[case(0)]
1433 #[case(FIXED_PRECISION)]
1434 fn test_valid_precision(#[case] precision: u8) {
1435 let result = check_fixed_precision(precision);
1436 assert!(result.is_ok());
1437 }
1438
1439 #[cfg(not(feature = "defi"))]
1440 #[rstest]
1441 fn test_invalid_precision() {
1442 let precision = FIXED_PRECISION + 1;
1443 let result = check_fixed_precision(precision);
1444 assert!(result.is_err());
1445 }
1446
1447 #[cfg(feature = "defi")]
1448 #[rstest]
1449 fn test_invalid_precision() {
1450 use crate::defi::WEI_PRECISION;
1451 let precision = WEI_PRECISION + 1;
1452 let result = check_fixed_precision(precision);
1453 assert!(result.is_err());
1454 }
1455
1456 #[rstest]
1457 fn test_check_float_precision_matches_supported_range() {
1458 for precision in 0..=u8::MAX {
1459 let expected = if precision <= MAX_FLOAT_PRECISION {
1460 Ok(())
1461 } else {
1462 Err(CorrectnessError::PredicateViolation {
1463 message: format!(
1464 "Fixed-point precision {precision} exceeds maximum float precision 16"
1465 ),
1466 })
1467 };
1468
1469 assert_eq!(check_float_precision(precision), expected);
1470 }
1471 }
1472
1473 #[rstest]
1474 fn test_check_float_precision_error_display() {
1475 let error = check_float_precision(18).unwrap_err();
1476
1477 assert_eq!(
1478 error.to_string(),
1479 "Fixed-point precision 18 exceeds maximum float precision 16"
1480 );
1481 }
1482
1483 #[cfg(not(feature = "defi"))]
1484 #[rstest]
1485 fn test_check_fixed_precision_returns_typed_error_with_stable_display() {
1486 let error = check_fixed_precision(FIXED_PRECISION + 1).unwrap_err();
1487
1488 assert_eq!(
1489 error,
1490 CorrectnessError::PredicateViolation {
1491 message: format!(
1492 "`precision` exceeded maximum `FIXED_PRECISION` ({FIXED_PRECISION}), was {}",
1493 FIXED_PRECISION + 1
1494 ),
1495 }
1496 );
1497 assert_eq!(
1498 error.to_string(),
1499 format!(
1500 "`precision` exceeded maximum `FIXED_PRECISION` ({FIXED_PRECISION}), was {}",
1501 FIXED_PRECISION + 1
1502 )
1503 );
1504 }
1505
1506 #[cfg(feature = "defi")]
1507 #[rstest]
1508 fn test_check_fixed_precision_returns_typed_error_with_stable_display() {
1509 use crate::defi::WEI_PRECISION;
1510
1511 let error = check_fixed_precision(WEI_PRECISION + 1).unwrap_err();
1512
1513 assert_eq!(
1514 error,
1515 CorrectnessError::PredicateViolation {
1516 message: format!(
1517 "`precision` exceeded maximum `WEI_PRECISION` (18), was {}",
1518 WEI_PRECISION + 1
1519 ),
1520 }
1521 );
1522 assert_eq!(
1523 error.to_string(),
1524 format!(
1525 "`precision` exceeded maximum `WEI_PRECISION` (18), was {}",
1526 WEI_PRECISION + 1
1527 )
1528 );
1529 }
1530
1531 #[rstest]
1532 #[case(0, 0.0)]
1533 #[case(1, 1.0)]
1534 #[case(1, 1.1)]
1535 #[case(9, 0.000_000_001)]
1536 #[case(16, 0.000_000_000_000_000_1)]
1537 #[case(0, -0.0)]
1538 #[case(1, -1.0)]
1539 #[case(1, -1.1)]
1540 #[case(9, -0.000_000_001)]
1541 #[case(16, -0.000_000_000_000_000_1)]
1542 fn test_f64_to_fixed_i128_to_fixed(#[case] precision: u8, #[case] value: f64) {
1543 let fixed = f64_to_fixed_i128(value, precision);
1544 let result = fixed_i128_to_f64(fixed);
1545 assert_eq!(result, value);
1546 }
1547
1548 #[rstest]
1549 #[case(0, 0.0)]
1550 #[case(1, 1.0)]
1551 #[case(1, 1.1)]
1552 #[case(9, 0.000_000_001)]
1553 #[case(16, 0.000_000_000_000_000_1)]
1554 fn test_f64_to_fixed_u128_to_fixed(#[case] precision: u8, #[case] value: f64) {
1555 let fixed = f64_to_fixed_u128(value, precision);
1556 let result = fixed_u128_to_f64(fixed);
1557 assert_eq!(result, value);
1558 }
1559
1560 #[rstest]
1561 #[case(0, 123_456.0)]
1562 #[case(0, 123_456.7)]
1563 #[case(0, 123_456.4)]
1564 #[case(1, 123_456.0)]
1565 #[case(1, 123_456.7)]
1566 #[case(1, 123_456.4)]
1567 #[case(2, 123_456.0)]
1568 #[case(2, 123_456.7)]
1569 #[case(2, 123_456.4)]
1570 fn test_f64_to_fixed_i128_with_precision(#[case] precision: u8, #[case] value: f64) {
1571 let result = f64_to_fixed_i128(value, precision);
1572
1573 let pow1 = 10_i128.pow(u32::from(precision));
1575 let pow2 = 10_i128.pow(u32::from(FIXED_PRECISION - precision));
1576 let rounded = (value * pow1 as f64).round() as i128;
1577 let expected = rounded * pow2;
1578
1579 assert_eq!(
1580 result, expected,
1581 "Failed for precision {precision}, value {value}: got {result}, expected {expected}"
1582 );
1583 }
1584
1585 #[rstest]
1586 #[case(0, 5.555_555_555_555_555)]
1587 #[case(1, 5.555_555_555_555_555)]
1588 #[case(2, 5.555_555_555_555_555)]
1589 #[case(3, 5.555_555_555_555_555)]
1590 #[case(4, 5.555_555_555_555_555)]
1591 #[case(5, 5.555_555_555_555_555)]
1592 #[case(6, 5.555_555_555_555_555)]
1593 #[case(7, 5.555_555_555_555_555)]
1594 #[case(8, 5.555_555_555_555_555)]
1595 #[case(9, 5.555_555_555_555_555)]
1596 #[case(10, 5.555_555_555_555_555)]
1597 #[case(11, 5.555_555_555_555_555)]
1598 #[case(12, 5.555_555_555_555_555)]
1599 #[case(13, 5.555_555_555_555_555)]
1600 #[case(14, 5.555_555_555_555_555)]
1601 #[case(15, 5.555_555_555_555_555)]
1602 #[case(0, -5.555_555_555_555_555)]
1603 #[case(1, -5.555_555_555_555_555)]
1604 #[case(2, -5.555_555_555_555_555)]
1605 #[case(3, -5.555_555_555_555_555)]
1606 #[case(4, -5.555_555_555_555_555)]
1607 #[case(5, -5.555_555_555_555_555)]
1608 #[case(6, -5.555_555_555_555_555)]
1609 #[case(7, -5.555_555_555_555_555)]
1610 #[case(8, -5.555_555_555_555_555)]
1611 #[case(9, -5.555_555_555_555_555)]
1612 #[case(10, -5.555_555_555_555_555)]
1613 #[case(11, -5.555_555_555_555_555)]
1614 #[case(12, -5.555_555_555_555_555)]
1615 #[case(13, -5.555_555_555_555_555)]
1616 #[case(14, -5.555_555_555_555_555)]
1617 #[case(15, -5.555_555_555_555_555)]
1618 fn test_f64_to_fixed_i128(#[case] precision: u8, #[case] value: f64) {
1619 if precision > FIXED_PRECISION {
1621 return;
1622 }
1623
1624 let result = f64_to_fixed_i128(value, precision);
1625
1626 let pow1 = 10_i128.pow(u32::from(precision));
1628 let pow2 = 10_i128.pow(u32::from(FIXED_PRECISION - precision));
1629 let rounded = (value * pow1 as f64).round() as i128;
1630 let expected = rounded * pow2;
1631
1632 assert_eq!(
1633 result, expected,
1634 "Failed for precision {precision}, value {value}: got {result}, expected {expected}"
1635 );
1636 }
1637
1638 #[rstest]
1639 #[case(0, 5.555_555_555_555_555)]
1640 #[case(1, 5.555_555_555_555_555)]
1641 #[case(2, 5.555_555_555_555_555)]
1642 #[case(3, 5.555_555_555_555_555)]
1643 #[case(4, 5.555_555_555_555_555)]
1644 #[case(5, 5.555_555_555_555_555)]
1645 #[case(6, 5.555_555_555_555_555)]
1646 #[case(7, 5.555_555_555_555_555)]
1647 #[case(8, 5.555_555_555_555_555)]
1648 #[case(9, 5.555_555_555_555_555)]
1649 #[case(10, 5.555_555_555_555_555)]
1650 #[case(11, 5.555_555_555_555_555)]
1651 #[case(12, 5.555_555_555_555_555)]
1652 #[case(13, 5.555_555_555_555_555)]
1653 #[case(14, 5.555_555_555_555_555)]
1654 #[case(15, 5.555_555_555_555_555)]
1655 #[case(16, 5.555_555_555_555_555)]
1656 fn test_f64_to_fixed_u64(#[case] precision: u8, #[case] value: f64) {
1657 if precision > FIXED_PRECISION {
1659 return;
1660 }
1661
1662 let result = f64_to_fixed_u128(value, precision);
1663
1664 let pow1 = 10_u128.pow(u32::from(precision));
1666 let pow2 = 10_u128.pow(u32::from(FIXED_PRECISION - precision));
1667 let rounded = (value * pow1 as f64).round() as u128;
1668 let expected = rounded * pow2;
1669
1670 assert_eq!(
1671 result, expected,
1672 "Failed for precision {precision}, value {value}: got {result}, expected {expected}"
1673 );
1674 }
1675
1676 #[rstest]
1677 fn test_fixed_i128_to_f64(
1678 #[values(1, -1, 2, -2, 10, -10, 100, -100, 1_000, -1_000, -10_000, -100_000)] value: i128,
1679 ) {
1680 assert_eq!(fixed_i128_to_f64(value), value as f64 / FIXED_SCALAR);
1681 }
1682
1683 #[rstest]
1684 fn test_fixed_u128_to_f64(
1685 #[values(
1686 0,
1687 1,
1688 2,
1689 3,
1690 10,
1691 100,
1692 1_000,
1693 10_000,
1694 100_000,
1695 1_000_000,
1696 10_000_000,
1697 100_000_000,
1698 1_000_000_000,
1699 10_000_000_000,
1700 100_000_000_000,
1701 1_000_000_000_000,
1702 10_000_000_000_000,
1703 100_000_000_000_000,
1704 1_000_000_000_000_000,
1705 10_000_000_000_000_000,
1706 100_000_000_000_000_000,
1707 1_000_000_000_000_000_000,
1708 10_000_000_000_000_000_000,
1709 100_000_000_000_000_000_000
1710 )]
1711 value: u128,
1712 ) {
1713 let result = fixed_u128_to_f64(value);
1714 assert_eq!(result, (value as f64) / FIXED_SCALAR);
1715 }
1716
1717 #[rstest]
1722 #[case(0, 0)] #[case(0, 10_000_000_000_000_000)] #[case(0, 1_200_000_000_000_000_000)] #[case(8, 12_345_678_900_000_000)] #[case(15, 1_234_567_890_123_450)] fn test_check_fixed_raw_u128_valid(#[case] precision: u8, #[case] raw: u128) {
1728 assert!(check_fixed_raw_u128(raw, precision).is_ok());
1729 }
1730
1731 #[rstest]
1732 #[case(0, 1)] #[case(0, 9_999_999_999_999_999)] #[case(0, 10_000_000_000_000_001)] #[case(8, 12_345_678_900_000_001)] #[case(15, 1_234_567_890_123_451)] fn test_check_fixed_raw_u128_invalid(#[case] precision: u8, #[case] raw: u128) {
1738 assert!(check_fixed_raw_u128(raw, precision).is_err());
1739 }
1740
1741 #[rstest]
1742 fn test_check_fixed_raw_u128_at_max_precision() {
1743 assert!(check_fixed_raw_u128(0, FIXED_PRECISION).is_ok());
1745 assert!(check_fixed_raw_u128(1, FIXED_PRECISION).is_ok());
1746 assert!(check_fixed_raw_u128(123_456_789, FIXED_PRECISION).is_ok());
1747 assert!(check_fixed_raw_u128(u128::MAX, FIXED_PRECISION).is_ok());
1748 }
1749
1750 #[rstest]
1751 #[case(0, 0)]
1752 #[case(0, 10_000_000_000_000_000)]
1753 #[case(0, -10_000_000_000_000_000)]
1754 #[case(8, 12_345_678_900_000_000)]
1755 #[case(8, -12_345_678_900_000_000)]
1756 fn test_check_fixed_raw_i128_valid(#[case] precision: u8, #[case] raw: i128) {
1757 assert!(check_fixed_raw_i128(raw, precision).is_ok());
1758 }
1759
1760 #[rstest]
1761 #[case(0, 1)]
1762 #[case(0, -1)]
1763 #[case(0, 9_999_999_999_999_999)]
1764 #[case(0, -9_999_999_999_999_999)]
1765 fn test_check_fixed_raw_i128_invalid(#[case] precision: u8, #[case] raw: i128) {
1766 assert!(check_fixed_raw_i128(raw, precision).is_err());
1767 }
1768
1769 #[rstest]
1770 fn test_check_fixed_raw_i128_at_max_precision() {
1771 assert!(check_fixed_raw_i128(0, FIXED_PRECISION).is_ok());
1772 assert!(check_fixed_raw_i128(1, FIXED_PRECISION).is_ok());
1773 assert!(check_fixed_raw_i128(-1, FIXED_PRECISION).is_ok());
1774 assert!(check_fixed_raw_i128(i128::MAX, FIXED_PRECISION).is_ok());
1775 assert!(check_fixed_raw_i128(i128::MIN, FIXED_PRECISION).is_ok());
1776 }
1777
1778 #[rstest]
1779 #[should_panic(expected = "Overflow when scaling f64 to fixed-point i128")]
1780 fn test_f64_to_fixed_i128_overflow_panics() {
1781 let _ = f64_to_fixed_i128(1e30, 0);
1782 }
1783
1784 #[rstest]
1785 #[should_panic(expected = "Overflow when scaling f64 to fixed-point u128")]
1786 fn test_f64_to_fixed_u128_overflow_panics() {
1787 let _ = f64_to_fixed_u128(1e30, 0);
1788 }
1789}
1790
1791#[cfg(not(feature = "high-precision"))]
1792#[cfg(test)]
1793mod tests {
1794 use nautilus_core::approx_eq;
1795 use rstest::rstest;
1796
1797 use super::*;
1798
1799 #[rstest]
1800 fn test_correct_raw_rounds_half_away_from_zero() {
1801 let precision = FIXED_PRECISION - 1;
1802
1803 assert_eq!(correct_raw_u128(20, precision), 20);
1804 assert_eq!(correct_raw_u128(14, precision), 10);
1805 assert_eq!(correct_raw_u128(15, precision), 20);
1806 assert_eq!(correct_raw_u64(14, precision), 10);
1807 assert_eq!(correct_raw_u64(15, precision), 20);
1808 assert_eq!(correct_raw_i128(15, precision), 20);
1809 assert_eq!(correct_raw_i128(-14, precision), -10);
1810 assert_eq!(correct_raw_i128(-15, precision), -20);
1811 assert_eq!(correct_raw_i64(15, precision), 20);
1812 assert_eq!(correct_raw_i64(-14, precision), -10);
1813 assert_eq!(correct_raw_i64(-15, precision), -20);
1814 }
1815
1816 #[rstest]
1817 fn test_f64_fixed_u128_round_trip() {
1818 let raw = f64_to_fixed_u128(1.5, 1);
1819
1820 assert_eq!(raw, 15 * 10_u128.pow(u32::from(FIXED_PRECISION - 1)));
1821 assert_eq!(fixed_u128_to_f64(raw), 1.5);
1822 }
1823
1824 #[rstest]
1825 fn test_mantissa_exponent_to_fixed_i128_allows_max_scale_factor() {
1826 let exponent = i8::try_from(38 - FIXED_PRECISION).unwrap();
1827
1828 assert_eq!(
1829 mantissa_exponent_to_fixed_i128(1, exponent, 0).unwrap(),
1830 10_i128.pow(38)
1831 );
1832 assert_eq!(
1833 mantissa_exponent_to_fixed_i128(1, exponent + 1, 0)
1834 .unwrap_err()
1835 .to_string(),
1836 format!(
1837 "Exponent {} produces scale factor 10^39 which exceeds i128 range",
1838 exponent + 1
1839 )
1840 );
1841 }
1842
1843 #[rstest]
1844 fn test_raw_scales_match_requires_equal_effective_scale() {
1845 assert!(raw_scales_match(0, FIXED_PRECISION));
1846 assert!(raw_scales_match(FIXED_PRECISION + 1, FIXED_PRECISION + 1));
1847 assert!(!raw_scales_match(FIXED_PRECISION, FIXED_PRECISION + 1));
1848 }
1849
1850 #[rstest]
1851 fn test_canonical_raw_trims_native_scale_trailing_zeros() {
1852 assert_eq!(
1853 canonical_raw(0_u128, FIXED_PRECISION + 2),
1854 (0, FIXED_PRECISION)
1855 );
1856 assert_eq!(
1857 canonical_raw(1_200_u128, FIXED_PRECISION + 2),
1858 (12, FIXED_PRECISION)
1859 );
1860 assert_eq!(
1861 canonical_raw(12_000_u128, FIXED_PRECISION + 2),
1862 (120, FIXED_PRECISION)
1863 );
1864 assert_eq!(
1865 canonical_raw(1_205_u128, FIXED_PRECISION + 2),
1866 (1_205, FIXED_PRECISION + 2)
1867 );
1868 assert_eq!(
1869 canonical_raw(5_u128, FIXED_PRECISION - 1),
1870 (5, FIXED_PRECISION)
1871 );
1872 }
1873
1874 #[rstest]
1875 fn test_compare_raw_zero_operands_are_equal_across_scales() {
1876 assert_eq!(compare_raw(0_u128, u8::MAX, 0_u128, 2), Ordering::Equal);
1877 }
1878
1879 #[rstest]
1880 fn test_precision_boundaries() {
1881 assert!(check_fixed_precision(0).is_ok());
1882 assert!(check_fixed_precision(FIXED_PRECISION).is_ok());
1883 assert!(check_fixed_precision(FIXED_PRECISION + 1).is_err());
1884 }
1885
1886 #[rstest]
1887 #[case(0.0)]
1888 #[case(1.0)]
1889 #[case(-1.0)]
1890 fn test_basic_roundtrip(#[case] value: f64) {
1891 for precision in 0..=FIXED_PRECISION {
1892 let fixed = f64_to_fixed_i64(value, precision);
1893 let result = fixed_i64_to_f64(fixed);
1894 assert!(approx_eq!(f64, value, result, epsilon = 0.001));
1895 }
1896 }
1897
1898 #[rstest]
1899 #[case(1_000_000.0)]
1900 #[case(-1_000_000.0)]
1901 fn test_large_value_roundtrip(#[case] value: f64) {
1902 for precision in 0..=FIXED_PRECISION {
1903 let fixed = f64_to_fixed_i64(value, precision);
1904 let result = fixed_i64_to_f64(fixed);
1905 assert!(approx_eq!(f64, value, result, epsilon = 0.000_1));
1906 }
1907 }
1908
1909 #[rstest]
1910 #[case(0, 123_456.0, 123_456_000_000_000)]
1911 #[case(0, 123_456.7, 123_457_000_000_000)]
1912 #[case(1, 123_456.7, 123_456_700_000_000)]
1913 #[case(2, 123_456.78, 123_456_780_000_000)]
1914 #[case(8, 123_456.123_456_78, 123_456_123_456_780)]
1915 #[case(9, 123_456.123_456_789, 123_456_123_456_789)]
1916 fn test_precision_specific_values(
1917 #[case] precision: u8,
1918 #[case] value: f64,
1919 #[case] expected: i64,
1920 ) {
1921 assert_eq!(f64_to_fixed_i64(value, precision), expected);
1922 }
1923
1924 #[rstest]
1925 #[case(0.0)]
1926 #[case(1.0)]
1927 #[case(1_000_000.0)]
1928 fn test_unsigned_basic_roundtrip(#[case] value: f64) {
1929 for precision in 0..=FIXED_PRECISION {
1930 let fixed = f64_to_fixed_u64(value, precision);
1931 let result = fixed_u64_to_f64(fixed);
1932 assert!(approx_eq!(f64, value, result, epsilon = 0.001));
1933 }
1934 }
1935
1936 #[rstest]
1937 #[case(0, 1.4, 1.0)]
1938 #[case(0, 1.5, 2.0)]
1939 #[case(0, 1.6, 2.0)]
1940 #[case(1, 1.44, 1.4)]
1941 #[case(1, 1.45, 1.5)]
1942 #[case(1, 1.46, 1.5)]
1943 #[case(2, 1.444, 1.44)]
1944 #[case(2, 1.445, 1.45)]
1945 #[case(2, 1.446, 1.45)]
1946 fn test_rounding(#[case] precision: u8, #[case] input: f64, #[case] expected: f64) {
1947 let fixed = f64_to_fixed_i128(input, precision);
1948 assert!(approx_eq!(
1949 f64,
1950 fixed_i128_to_f64(fixed),
1951 expected,
1952 epsilon = 0.000_000_001
1953 ));
1954 }
1955
1956 #[rstest]
1957 fn test_special_values() {
1958 assert_eq!(f64_to_fixed_i128(0.0, FIXED_PRECISION), 0);
1960 assert_eq!(f64_to_fixed_i128(-0.0, FIXED_PRECISION), 0);
1961
1962 let smallest_positive = 1.0 / FIXED_SCALAR;
1964 let fixed_smallest = f64_to_fixed_i128(smallest_positive, FIXED_PRECISION);
1965 assert_eq!(fixed_smallest, 1);
1966
1967 let large_int = 1_000_000_000.0;
1969 let fixed_large = f64_to_fixed_i128(large_int, 0);
1970 assert_eq!(fixed_i128_to_f64(fixed_large), large_int);
1971 }
1972
1973 #[rstest]
1974 #[case(0)]
1975 #[case(FIXED_PRECISION)]
1976 fn test_valid_precision(#[case] precision: u8) {
1977 let result = check_fixed_precision(precision);
1978 assert!(result.is_ok());
1979 }
1980
1981 #[rstest]
1982 fn test_invalid_precision() {
1983 let precision = FIXED_PRECISION + 1;
1984 let result = check_fixed_precision(precision);
1985 assert!(result.is_err());
1986 }
1987
1988 #[rstest]
1989 #[case(0, 0.0)]
1990 #[case(1, 1.0)]
1991 #[case(1, 1.1)]
1992 #[case(9, 0.000_000_001)]
1993 #[case(0, -0.0)]
1994 #[case(1, -1.0)]
1995 #[case(1, -1.1)]
1996 #[case(9, -0.000_000_001)]
1997 fn test_f64_to_fixed_i64_to_fixed(#[case] precision: u8, #[case] value: f64) {
1998 let fixed = f64_to_fixed_i64(value, precision);
1999 let result = fixed_i64_to_f64(fixed);
2000 assert_eq!(result, value);
2001 }
2002
2003 #[rstest]
2004 #[case(0, 0.0)]
2005 #[case(1, 1.0)]
2006 #[case(1, 1.1)]
2007 #[case(9, 0.000_000_001)]
2008 fn test_f64_to_fixed_u64_to_fixed(#[case] precision: u8, #[case] value: f64) {
2009 let fixed = f64_to_fixed_u64(value, precision);
2010 let result = fixed_u64_to_f64(fixed);
2011 assert_eq!(result, value);
2012 }
2013
2014 #[rstest]
2015 #[case(0, 123_456.0, 123_456_000_000_000)]
2016 #[case(0, 123_456.7, 123_457_000_000_000)]
2017 #[case(0, 123_456.4, 123_456_000_000_000)]
2018 #[case(1, 123_456.0, 123_456_000_000_000)]
2019 #[case(1, 123_456.7, 123_456_700_000_000)]
2020 #[case(1, 123_456.4, 123_456_400_000_000)]
2021 #[case(2, 123_456.0, 123_456_000_000_000)]
2022 #[case(2, 123_456.7, 123_456_700_000_000)]
2023 #[case(2, 123_456.4, 123_456_400_000_000)]
2024 fn test_f64_to_fixed_i64_with_precision(
2025 #[case] precision: u8,
2026 #[case] value: f64,
2027 #[case] expected: i64,
2028 ) {
2029 assert_eq!(f64_to_fixed_i64(value, precision), expected);
2030 }
2031
2032 #[rstest]
2033 #[case(0, 5.5, 6_000_000_000)]
2034 #[case(1, 5.55, 5_600_000_000)]
2035 #[case(2, 5.555, 5_560_000_000)]
2036 #[case(3, 5.5555, 5_556_000_000)]
2037 #[case(4, 5.55555, 5_555_600_000)]
2038 #[case(5, 5.555_555, 5_555_560_000)]
2039 #[case(6, 5.555_555_5, 5_555_556_000)]
2040 #[case(7, 5.555_555_55, 5_555_555_600)]
2041 #[case(8, 5.555_555_555, 5_555_555_560)]
2042 #[case(9, 5.555_555_555_5, 5_555_555_556)]
2043 #[case(0, -5.5, -6_000_000_000)]
2044 #[case(1, -5.55, -5_600_000_000)]
2045 #[case(2, -5.555, -5_560_000_000)]
2046 #[case(3, -5.5555, -5_556_000_000)]
2047 #[case(4, -5.55555, -5_555_600_000)]
2048 #[case(5, -5.555_555, -5_555_560_000)]
2049 #[case(6, -5.555_555_5, -5_555_556_000)]
2050 #[case(7, -5.555_555_55, -5_555_555_600)]
2051 #[case(8, -5.555_555_555, -5_555_555_560)]
2052 #[case(9, -5.555_555_555_5, -5_555_555_556)]
2053 fn test_f64_to_fixed_i64(#[case] precision: u8, #[case] value: f64, #[case] expected: i64) {
2054 assert_eq!(f64_to_fixed_i64(value, precision), expected);
2055 }
2056
2057 #[rstest]
2058 #[case(0, 5.5, 6_000_000_000)]
2059 #[case(1, 5.55, 5_600_000_000)]
2060 #[case(2, 5.555, 5_560_000_000)]
2061 #[case(3, 5.5555, 5_556_000_000)]
2062 #[case(4, 5.55555, 5_555_600_000)]
2063 #[case(5, 5.555_555, 5_555_560_000)]
2064 #[case(6, 5.555_555_5, 5_555_556_000)]
2065 #[case(7, 5.555_555_55, 5_555_555_600)]
2066 #[case(8, 5.555_555_555, 5_555_555_560)]
2067 #[case(9, 5.555_555_555_5, 5_555_555_556)]
2068 fn test_f64_to_fixed_u64(#[case] precision: u8, #[case] value: f64, #[case] expected: u64) {
2069 assert_eq!(f64_to_fixed_u64(value, precision), expected);
2070 }
2071
2072 #[rstest]
2073 fn test_fixed_i64_to_f64(
2074 #[values(1, -1, 2, -2, 10, -10, 100, -100, 1_000, -1_000)] value: i64,
2075 ) {
2076 assert_eq!(fixed_i64_to_f64(value), value as f64 / FIXED_SCALAR);
2077 }
2078
2079 #[rstest]
2080 fn test_fixed_u64_to_f64(
2081 #[values(
2082 0,
2083 1,
2084 2,
2085 3,
2086 10,
2087 100,
2088 1_000,
2089 10_000,
2090 100_000,
2091 1_000_000,
2092 10_000_000,
2093 100_000_000,
2094 1_000_000_000,
2095 10_000_000_000,
2096 100_000_000_000,
2097 1_000_000_000_000,
2098 10_000_000_000_000,
2099 100_000_000_000_000,
2100 1_000_000_000_000_000
2101 )]
2102 value: u64,
2103 ) {
2104 let result = fixed_u64_to_f64(value);
2105 assert_eq!(result, (value as f64) / FIXED_SCALAR);
2106 }
2107
2108 #[rstest]
2109 #[case(0, 0)] #[case(0, 1_000_000_000)] #[case(0, 120_000_000_000)] #[case(2, 123_450_000_000)] #[case(8, 1_234_567_890)] fn test_check_fixed_raw_u64_valid(#[case] precision: u8, #[case] raw: u64) {
2115 assert!(check_fixed_raw_u64(raw, precision).is_ok());
2116 }
2117
2118 #[rstest]
2119 #[case(0, 1)] #[case(0, 999_999_999)] #[case(0, 1_000_000_001)] #[case(0, 119_582_001_968_421_736)] #[case(2, 123_456_789_000)] #[case(8, 1_234_567_891)] fn test_check_fixed_raw_u64_invalid(#[case] precision: u8, #[case] raw: u64) {
2126 assert!(check_fixed_raw_u64(raw, precision).is_err());
2127 }
2128
2129 #[rstest]
2130 fn test_check_fixed_raw_u64_at_max_precision() {
2131 assert!(check_fixed_raw_u64(0, FIXED_PRECISION).is_ok());
2133 assert!(check_fixed_raw_u64(1, FIXED_PRECISION).is_ok());
2134 assert!(check_fixed_raw_u64(123_456_789, FIXED_PRECISION).is_ok());
2135 assert!(check_fixed_raw_u64(u64::MAX, FIXED_PRECISION).is_ok());
2136 }
2137
2138 #[rstest]
2139 #[case(0, 0)]
2140 #[case(0, 1_000_000_000)]
2141 #[case(0, -1_000_000_000)]
2142 #[case(2, 123_450_000_000)]
2143 #[case(2, -123_450_000_000)]
2144 fn test_check_fixed_raw_i64_valid(#[case] precision: u8, #[case] raw: i64) {
2145 assert!(check_fixed_raw_i64(raw, precision).is_ok());
2146 }
2147
2148 #[rstest]
2149 #[case(0, 1)]
2150 #[case(0, -1)]
2151 #[case(0, 999_999_999)]
2152 #[case(0, -999_999_999)]
2153 fn test_check_fixed_raw_i64_invalid(#[case] precision: u8, #[case] raw: i64) {
2154 assert!(check_fixed_raw_i64(raw, precision).is_err());
2155 }
2156
2157 #[rstest]
2158 fn test_check_fixed_raw_i64_at_max_precision() {
2159 assert!(check_fixed_raw_i64(0, FIXED_PRECISION).is_ok());
2160 assert!(check_fixed_raw_i64(1, FIXED_PRECISION).is_ok());
2161 assert!(check_fixed_raw_i64(-1, FIXED_PRECISION).is_ok());
2162 assert!(check_fixed_raw_i64(i64::MAX, FIXED_PRECISION).is_ok());
2163 assert!(check_fixed_raw_i64(i64::MIN, FIXED_PRECISION).is_ok());
2164 }
2165
2166 #[rstest]
2167 #[should_panic(expected = "Overflow when scaling f64 to fixed-point i64")]
2168 fn test_f64_to_fixed_i64_overflow_panics() {
2169 let _ = f64_to_fixed_i64(2e18, 0);
2170 }
2171
2172 #[rstest]
2173 #[should_panic(expected = "Overflow when scaling f64 to fixed-point u64")]
2174 fn test_f64_to_fixed_u64_overflow_panics() {
2175 let _ = f64_to_fixed_u64(2e19, 0);
2176 }
2177}
2178
2179#[cfg(test)]
2180mod bankers_round_tests {
2181 use std::str::FromStr;
2182
2183 use rstest::rstest;
2184 use rust_decimal::{Decimal, RoundingStrategy};
2185
2186 use super::*;
2187
2188 #[rstest]
2189 #[case(0, 0, 0)]
2191 #[case(1, 0, 1)]
2192 #[case(5, 0, 5)]
2193 #[case(99, 0, 99)]
2194 #[case(-7, 0, -7)]
2195 #[case(12345, 39, 0)]
2197 #[case(i128::from(i64::MAX), 100, 0)]
2198 #[case(-99999, 50, 0)]
2199 #[case(15, 1, 2)] #[case(25, 1, 2)] #[case(35, 1, 4)] #[case(45, 1, 4)] #[case(55, 1, 6)] #[case(65, 1, 6)] #[case(75, 1, 8)] #[case(85, 1, 8)] #[case(95, 1, 10)] #[case(105, 1, 10)] #[case(14, 1, 1)] #[case(16, 1, 2)] #[case(24, 1, 2)] #[case(26, 1, 3)] #[case(11, 1, 1)] #[case(19, 1, 2)] #[case(150, 2, 2)] #[case(250, 2, 2)] #[case(350, 2, 4)] #[case(450, 2, 4)] #[case(550, 2, 6)] #[case(1050, 2, 10)] #[case(1150, 2, 12)] #[case(149, 2, 1)] #[case(151, 2, 2)] #[case(199, 2, 2)] #[case(101, 2, 1)] #[case(1500, 3, 2)] #[case(2500, 3, 2)] #[case(3500, 3, 4)] #[case(10500, 3, 10)] #[case(11500, 3, 12)] #[case(1499, 3, 1)] #[case(1501, 3, 2)] #[case(-15, 1, -2)] #[case(-25, 1, -2)] #[case(-35, 1, -4)] #[case(-45, 1, -4)] #[case(-55, 1, -6)] #[case(-65, 1, -6)] #[case(-150, 2, -2)] #[case(-250, 2, -2)] #[case(-350, 2, -4)] #[case(-14, 1, -1)] #[case(-16, 1, -2)] #[case(-24, 1, -2)] #[case(-26, 1, -3)] #[case(0, 1, 0)]
2256 #[case(0, 2, 0)]
2257 #[case(0, 5, 0)]
2258 #[case(123_456_789, 3, 123_457)] #[case(123_456_500, 3, 123_456)] #[case(123_457_500, 3, 123_458)] #[case(100_005, 1, 10_000)] #[case(100_015, 1, 10_002)] #[case(999_999_999_999_999_995, 1, 100_000_000_000_000_000)]
2266 #[case(1_000_000_000_000_000_005, 1, 100_000_000_000_000_000)]
2267 fn test_bankers_round(#[case] mantissa: i128, #[case] excess: u32, #[case] expected: i128) {
2268 assert_eq!(
2269 bankers_round(mantissa, excess),
2270 expected,
2271 "bankers_round({mantissa}, {excess}) expected {expected}"
2272 );
2273 }
2274
2275 #[rstest]
2277 #[case(15, 1)]
2278 #[case(25, 1)]
2279 #[case(35, 1)]
2280 #[case(150, 2)]
2281 #[case(250, 2)]
2282 #[case(1500, 3)]
2283 #[case(2500, 3)]
2284 #[case(123_456_789, 3)]
2285 #[case(14, 1)]
2286 #[case(16, 1)]
2287 fn test_bankers_round_negative_symmetry(#[case] mantissa: i128, #[case] excess: u32) {
2288 assert_eq!(
2289 bankers_round(-mantissa, excess),
2290 -bankers_round(mantissa, excess),
2291 "Negative symmetry failed for mantissa={mantissa}, excess={excess}"
2292 );
2293 }
2294
2295 #[rstest]
2297 #[case("1.005", 2, "1.00")] #[case("1.015", 2, "1.02")] #[case("1.025", 2, "1.02")] #[case("1.035", 2, "1.04")] #[case("1.045", 2, "1.04")] #[case("2.5", 0, "2")] #[case("3.5", 0, "4")] #[case("-2.5", 0, "-2")]
2305 #[case("-3.5", 0, "-4")]
2306 #[case("123.456", 2, "123.46")]
2307 #[case("123.455", 2, "123.46")] #[case("123.445", 2, "123.44")] fn test_bankers_round_matches_decimal(
2310 #[case] input: &str,
2311 #[case] target_precision: u8,
2312 #[case] expected: &str,
2313 ) {
2314 let dec = Decimal::from_str(input).unwrap();
2315 let expected_dec = Decimal::from_str(expected).unwrap();
2316
2317 let decimal_rounded = dec.round_dp_with_strategy(
2318 u32::from(target_precision),
2319 RoundingStrategy::MidpointNearestEven,
2320 );
2321 assert_eq!(
2322 decimal_rounded, expected_dec,
2323 "Decimal rounding sanity check failed for {input}"
2324 );
2325
2326 let mantissa = dec.mantissa();
2327 let scale = dec.scale() as u8;
2328 let excess = u32::from(scale.saturating_sub(target_precision));
2329 if excess > 0 {
2330 let rounded = bankers_round(mantissa, excess);
2331
2332 let expected_mantissa = expected_dec.mantissa();
2334 let expected_scale = expected_dec.scale() as u8;
2335 let scale_diff = u32::from(target_precision.saturating_sub(expected_scale));
2336 let normalized_expected = expected_mantissa * 10i128.pow(scale_diff);
2337
2338 assert_eq!(
2339 rounded, normalized_expected,
2340 "bankers_round disagrees with Decimal for {input} at precision {target_precision}"
2341 );
2342 }
2343 }
2344}
2345
2346#[cfg(test)]
2347mod correct_raw_tests {
2348 use rstest::rstest;
2349
2350 use super::*;
2351
2352 #[rstest]
2356 #[case(0, 0)]
2357 #[case(10, 10)] #[case(14, 10)] #[case(15, 20)] #[case(16, 20)] #[case(u64::MAX, u64::MAX - 5)] fn test_correct_raw_u64(#[case] raw: u64, #[case] expected: u64) {
2363 assert_eq!(correct_raw_u64(raw, FIXED_PRECISION - 1), expected);
2364 }
2365
2366 #[rstest]
2367 #[case(0, 0)]
2368 #[case(14, 10)]
2369 #[case(15, 20)]
2370 #[case(-14, -10)] #[case(-15, -20)] #[case(-16, -20)] #[case(i64::MAX, i64::MAX - 7)] #[case(i64::MIN, i64::MIN + 8)] fn test_correct_raw_i64(#[case] raw: i64, #[case] expected: i64) {
2376 assert_eq!(correct_raw_i64(raw, FIXED_PRECISION - 1), expected);
2377 }
2378
2379 #[rstest]
2380 #[case(0, 0)]
2381 #[case(14, 10)]
2382 #[case(15, 20)]
2383 #[case(u128::MAX, u128::MAX - 5)] fn test_correct_raw_u128(#[case] raw: u128, #[case] expected: u128) {
2385 assert_eq!(correct_raw_u128(raw, FIXED_PRECISION - 1), expected);
2386 }
2387
2388 #[rstest]
2389 #[case(0, 0)]
2390 #[case(14, 10)]
2391 #[case(15, 20)]
2392 #[case(-15, -20)]
2393 #[case(i128::MAX, i128::MAX - 7)] #[case(i128::MIN, i128::MIN + 8)] fn test_correct_raw_i128(#[case] raw: i128, #[case] expected: i128) {
2396 assert_eq!(correct_raw_i128(raw, FIXED_PRECISION - 1), expected);
2397 }
2398
2399 #[rstest]
2400 fn test_correct_raw_identity_at_max_precision() {
2401 assert_eq!(correct_raw_u64(12_345, FIXED_PRECISION), 12_345);
2402 assert_eq!(correct_raw_i64(-12_345, FIXED_PRECISION), -12_345);
2403 assert_eq!(correct_raw_u128(12_345, FIXED_PRECISION), 12_345);
2404 assert_eq!(correct_raw_i128(-12_345, FIXED_PRECISION), -12_345);
2405 }
2406}
2407
2408#[cfg(test)]
2409mod checked_mul_div_tests {
2410 #[cfg(feature = "defi")]
2411 use alloy_primitives::U256;
2412 use proptest::{prelude::*, test_runner::Config as ProptestConfig};
2413 use rstest::rstest;
2414
2415 use super::{FIXED_SCALAR_RAW, checked_mul_div_fixed};
2416 use crate::types::quantity::QuantityRaw;
2417
2418 #[rstest]
2419 fn test_checked_mul_div_fixed_exact_boundaries() {
2420 let scalar = FIXED_SCALAR_RAW;
2421
2422 assert_eq!(checked_mul_div_fixed(0, QuantityRaw::MAX), Some(0));
2423 assert_eq!(checked_mul_div_fixed(QuantityRaw::MAX, 0), Some(0));
2424 assert_eq!(checked_mul_div_fixed(scalar, scalar), Some(scalar));
2425 assert_eq!(
2426 checked_mul_div_fixed(scalar - 1, scalar - 1),
2427 Some(scalar - 2)
2428 );
2429 assert_eq!(
2430 checked_mul_div_fixed(scalar + 1, scalar + 1),
2431 Some(scalar + 2)
2432 );
2433 assert_eq!(
2434 checked_mul_div_fixed(QuantityRaw::MAX, scalar),
2435 Some(QuantityRaw::MAX)
2436 );
2437 assert_eq!(
2438 checked_mul_div_fixed(scalar, QuantityRaw::MAX),
2439 Some(QuantityRaw::MAX)
2440 );
2441 assert_eq!(checked_mul_div_fixed(QuantityRaw::MAX, scalar + 1), None);
2442 assert_eq!(checked_mul_div_fixed(scalar + 1, QuantityRaw::MAX), None);
2443 }
2444
2445 #[cfg(not(feature = "high-precision"))]
2446 proptest! {
2447 #![proptest_config(ProptestConfig::with_cases(4_096))]
2448
2449 #[rstest]
2450 fn prop_checked_mul_div_fixed_matches_u128_full_range(
2451 lhs in any::<QuantityRaw>(),
2452 rhs in any::<QuantityRaw>(),
2453 ) {
2454 let expected = u128::from(lhs)
2455 .checked_mul(u128::from(rhs))
2456 .map(|product| product / u128::from(FIXED_SCALAR_RAW))
2457 .and_then(|result| QuantityRaw::try_from(result).ok());
2458
2459 prop_assert_eq!(checked_mul_div_fixed(lhs, rhs), expected);
2460 }
2461
2462 #[rstest]
2463 fn prop_checked_mul_div_fixed_matches_u128_final_fit(
2464 (lhs, rhs) in standard_final_fit_strategy(),
2465 ) {
2466 let expected =
2467 u128::from(lhs) * u128::from(rhs) / u128::from(FIXED_SCALAR_RAW);
2468 let expected = QuantityRaw::try_from(expected).expect("strategy result fits u64");
2469
2470 prop_assert_eq!(checked_mul_div_fixed(lhs, rhs), Some(expected));
2471 }
2472
2473 #[rstest]
2474 fn prop_checked_mul_div_fixed_avoids_u64_phantom_overflow(
2475 (lhs, rhs, expected) in standard_phantom_overflow_strategy(),
2476 ) {
2477 prop_assert!(lhs.checked_mul(rhs).is_none());
2478 prop_assert_eq!(checked_mul_div_fixed(lhs, rhs), Some(expected));
2479 }
2480 }
2481
2482 #[cfg(feature = "high-precision")]
2483 proptest! {
2484 #![proptest_config(ProptestConfig::with_cases(4_096))]
2485
2486 #[rstest]
2487 fn prop_checked_mul_div_fixed_matches_u128_ordinary(
2488 (lhs, rhs) in high_precision_ordinary_strategy(),
2489 ) {
2490 let expected = lhs
2491 .checked_mul(rhs)
2492 .expect("ordinary strategy product fits u128")
2493 / FIXED_SCALAR_RAW;
2494
2495 prop_assert_eq!(checked_mul_div_fixed(lhs, rhs), Some(expected));
2496 }
2497
2498 #[rstest]
2499 fn prop_checked_mul_div_fixed_avoids_u128_phantom_overflow(
2500 (lhs, rhs, expected) in high_precision_phantom_overflow_strategy(),
2501 ) {
2502 prop_assert!(lhs.checked_mul(rhs).is_none());
2503 prop_assert_eq!(checked_mul_div_fixed(lhs, rhs), Some(expected));
2504 }
2505
2506 #[rstest]
2507 fn prop_checked_mul_div_fixed_handles_remainders_after_u128_overflow(
2508 rhs in high_precision_remainder_overflow_strategy(),
2509 ) {
2510 let lhs = 2 * FIXED_SCALAR_RAW - 1;
2511 let expected = 2 * rhs - rhs.div_ceil(FIXED_SCALAR_RAW);
2512
2513 prop_assert!(lhs.checked_mul(rhs).is_none());
2514 prop_assert_ne!(lhs % FIXED_SCALAR_RAW, 0);
2515 prop_assert_ne!(rhs % FIXED_SCALAR_RAW, 0);
2516 prop_assert_eq!(checked_mul_div_fixed(lhs, rhs), Some(expected));
2517 prop_assert_eq!(checked_mul_div_fixed(rhs, lhs), Some(expected));
2518 }
2519
2520 #[rstest]
2521 fn prop_checked_mul_div_fixed_is_commutative(
2522 lhs in any::<QuantityRaw>(),
2523 rhs in any::<QuantityRaw>(),
2524 ) {
2525 prop_assert_eq!(
2526 checked_mul_div_fixed(lhs, rhs),
2527 checked_mul_div_fixed(rhs, lhs)
2528 );
2529 }
2530 }
2531
2532 #[cfg(feature = "defi")]
2533 proptest! {
2534 #![proptest_config(ProptestConfig::with_cases(4_096))]
2535
2536 #[rstest]
2537 fn prop_checked_mul_div_raw_matches_u256_full_range(
2538 lhs in any::<QuantityRaw>(),
2539 rhs in any::<QuantityRaw>(),
2540 precision in 16_u32..=18,
2541 ) {
2542 let scalar = 10_u128.pow(precision);
2543 let expected = U256::from(lhs) * U256::from(rhs) / U256::from(scalar);
2544 let expected = QuantityRaw::try_from(expected).ok();
2545 prop_assert_eq!(super::checked_mul_div_raw(lhs, rhs, scalar), expected);
2546 }
2547
2548 #[rstest]
2549 fn prop_checked_mul_div_fixed_matches_u256_full_range(
2550 lhs in any::<QuantityRaw>(),
2551 rhs in any::<QuantityRaw>(),
2552 ) {
2553 let expected = U256::from(lhs)
2554 .checked_mul(U256::from(rhs))
2555 .expect("u128 product fits U256")
2556 / U256::from(FIXED_SCALAR_RAW);
2557 let expected = QuantityRaw::try_from(expected).ok();
2558
2559 prop_assert_eq!(checked_mul_div_fixed(lhs, rhs), expected);
2560 }
2561 }
2562
2563 #[cfg(not(feature = "high-precision"))]
2564 fn standard_final_fit_strategy() -> impl Strategy<Value = (QuantityRaw, QuantityRaw)> {
2565 let scalar = FIXED_SCALAR_RAW;
2566
2567 (0_u64..=1_000, 0_u64..=1_000, 0_u64..scalar, 0_u64..scalar).prop_map(
2568 move |(lhs_whole, rhs_whole, lhs_remainder, rhs_remainder)| {
2569 (
2570 lhs_whole * scalar + lhs_remainder,
2571 rhs_whole * scalar + rhs_remainder,
2572 )
2573 },
2574 )
2575 }
2576
2577 #[cfg(not(feature = "high-precision"))]
2578 fn standard_phantom_overflow_strategy()
2579 -> impl Strategy<Value = (QuantityRaw, QuantityRaw, QuantityRaw)> {
2580 let scalar = FIXED_SCALAR_RAW;
2581
2582 (8_000_000_000_u64..=9_000_000_000, 0_u64..scalar).prop_map(
2583 move |(lhs_whole, rhs_remainder)| {
2584 let lhs = lhs_whole * scalar;
2585 let rhs = scalar + rhs_remainder;
2586 (lhs, rhs, lhs_whole * rhs)
2587 },
2588 )
2589 }
2590
2591 #[cfg(feature = "high-precision")]
2592 fn high_precision_ordinary_strategy() -> impl Strategy<Value = (QuantityRaw, QuantityRaw)> {
2593 let scalar = FIXED_SCALAR_RAW;
2594
2595 (
2596 0_u128..=1_000,
2597 0_u128..=1_000,
2598 0_u128..scalar,
2599 0_u128..scalar,
2600 )
2601 .prop_map(
2602 move |(lhs_whole, rhs_whole, lhs_remainder, rhs_remainder)| {
2603 (
2604 lhs_whole * scalar + lhs_remainder,
2605 rhs_whole * scalar + rhs_remainder,
2606 )
2607 },
2608 )
2609 }
2610
2611 #[cfg(feature = "high-precision")]
2612 fn high_precision_phantom_overflow_strategy()
2613 -> impl Strategy<Value = (QuantityRaw, QuantityRaw, QuantityRaw)> {
2614 let scalar = FIXED_SCALAR_RAW;
2615
2616 (10_000_u128..=1_000_000, 1_000_u128..=10_000, 0_u128..scalar).prop_map(
2617 move |(lhs_whole, rhs_whole, rhs_remainder)| {
2618 let lhs = lhs_whole * scalar;
2619 let rhs = rhs_whole * scalar + rhs_remainder;
2620 (lhs, rhs, lhs_whole * rhs)
2621 },
2622 )
2623 }
2624
2625 #[cfg(feature = "high-precision")]
2626 fn high_precision_remainder_overflow_strategy() -> impl Strategy<Value = QuantityRaw> {
2627 let lhs = 2 * FIXED_SCALAR_RAW - 1;
2628 let min = QuantityRaw::MAX / lhs + 1;
2629
2630 (min..=QuantityRaw::MAX / 2).prop_filter("rhs remainder is nonzero", |rhs| {
2631 rhs % FIXED_SCALAR_RAW != 0
2632 })
2633 }
2634}